[英]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()
它完美地工作,每個線程在發送發布請求后自行結束。 我用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("%.8lf\n", 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 multi API 。 它使用異步套接字而不是線程。
以下是如何使用 curl multi API 的一些示例: multi-poll.c和10-at-a-time.c
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.