在C++中使用cURL和多线程
Using cURL and multi threading in C++
我有一个POST请求,我想在没有任何时间偏移的情况下重复它。我已经在python
中用requests
完成了它。
import requests
import json
url = 'SOME URL'
headers = {"headers"}
payload ={"some payload here"}
data = json.dumps(payload)
session = requests.Session()
def SendOrder():
r = session.post(url,data=data,headers=headers)
print(r.text)
for i in range(2000):
Thread(target=SendOrder,args=[]).start()
它完美地工作,每个线程在发送post请求后自行结束。我用cURL
:在C++中实现
int Requst(CURL *curl) {
curl_easy_perform(curl);
double tt = 0.000;
int curlRC = curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &tt);
printf("%.8lfn", tt);
return 0;
}
curl_global_init(CURL_GLOBAL_ALL);
CURL *curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1);
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
chunk = curl_slist_append(chunk, "user-agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36");
chunk = curl_slist_append(chunk, "x-requested-with:XMLHttpRequest");
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
std::string jsonstr = "PAYLOAD";
curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 2L);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonstr.c_str());
curl_easy_setopt(curl, CURLOPT_URL, "url");
for (int i = 1; i <= 1000; i++) {
std::thread(Requst, curl);
}
curl_easy_cleanup(curl);
curl_global_cleanup();
我想在调用Request
之后线程结束自己。我不太懂C++。或者无论如何都要制作类似python代码的东西?谢谢
std::thread
只是一个围绕本机(实际(线程的包装类。您应该在销毁std::thread
实例之前将其保留在身边,并将join()
与之一起,否则std::thread
的析构函数将中止程序。
您还应该在线程内调用curl_easy_*
。
像这样的
std::vector<std::thread> threads;
for (int i = 1; i <= 1000; i++) {
threads.emplace_back([&]{ // creates and starts a thread
CURL *curl = curl_easy_init();
curl_easy_setopt(...
. . .
curl_easy_perform();
curl_easy_cleanup(curl);
});
}
for (auto& t : threads) { // wait for all threads to finish
t.join();
}
话虽如此,为了获得良好的性能,最好使用curl多API。它使用异步套接字而不是线程。
下面是一些如何使用curl多API的示例:multi-poll.c和10-at-time.c
相关文章:
- 在C++中使用cURL和多线程
- 多线程双缓冲区
- 为什么我的多线程作业队列崩溃
- 在main()之外初始化std::vector会导致性能下降(多线程)
- 试图创建一个多线程程序来查找0-100000000之间的总素数
- 为什么一个向量上的多线程操作很慢
- 学习多线程C++:添加线程不会使执行速度更快,即使它看起来应该
- 全局变量 多读取器 一个写入器多线程安全?
- boost::文件系统::recursive_directory_iterator多线程安全
- 如何阻止TensorFlow的多线程
- 如何在多线程中正确使用unique_ptr进行多态性?
- 并发/多线程:是否可以以这种方式生成相同的输出?
- sigwait() 在多线程程序中不起作用
- 多线程程序中出现意外的内存泄漏
- 静态 constexpr 类成员变量对多线程读取是否安全?
- 多线程比没有线程C++慢
- 具有 C++11 多线程的特征库
- 通过安装信号处理程序关闭多线程应用程序
- 在多线程中使用curl句柄的错误工作方法的替代方法
- 多线程curl请求的段错误