c++ - 发出并行的 libcurl HTTP 请求

标签 c++ multithreading libcurl http-request

我对使用 libcurl (C++) 执行并行 HTTP 请求的安全性有疑问。阅读此问题时,请记住我对 HTTP 请求的一般了解有限。

基本上,假设我有两个(或更多)线程,每个线程每秒发出一次 HTTP 请求。 (所有请求都发送到同一台服务器)。我的程序(或其他程序?)如何跟踪 HTTP 响应属于哪个胎面?我的意思是,我可以确定如果请求 A 是从线程 1 发送的,并且同时从线程 2 请求 B,并且同时检索响应,那么正确的响应(响应 A)会转到线程 1 并且对线程 2 的响应 B?

请原谅我对这件事的无知。

谢谢。

最佳答案

首先libcurl是thread safe :

libcurl is designed and implemented entirely thread safe

正如官方文档所指出的,您需要做的是:

Never share libcurl handles between multiple threads. You should only use one handle in one single thread at any given time.

另外还有这个official FAQ entry提供了更多的精度,例如,如果您打算使用 SSL:

If you use a OpenSSL-powered libcurl in a multi-threaded environment, you need to provide one or two locking functions

如您所见,有一个官方示例说明了简单句柄的多线程使用:参见 multithread.c :

/* This is the callback executed when a new threads starts */
static void *pull_one_url(void *url)
{
  CURL *curl;

  curl = curl_easy_init();
  curl_easy_setopt(curl, CURLOPT_URL, url);
  curl_easy_perform(curl); /* ignores error */ 
  curl_easy_cleanup(curl);

  return NULL;
}

/* ... */

/* This is the main loop that creates `NUMT` threads for parallel fetching */
for(i=0; i< NUMT; i++) {
    error = pthread_create(&tid[i],
                           NULL, /* default attributes please */ 
                           pull_one_url,
                           (void *)urls[i]);
  /* ... */
}

所以请随意尝试这个例子。

最后请记住,libcurl 还提供了所谓的 multi interface使用单个线程提供多个传输。根据您的用例,您可能会发现它也很方便。

编辑

关于 OpenSSL + 多线程,有一些具体的官方示例可能会有所帮助:

关于c++ - 发出并行的 libcurl HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28695666/

相关文章:

c - 使用 libcurl 在 C 中进行 JSON 请求

c - 错误 : unknown type name 'CURL'

c++ - libcurl curl_easy_perform 崩溃(段错误)c++

c++ - 在 C++ 98 中优化 vector 过滤

java - 干扰线程

Java ConcurrentHashMap 原子获取和放置

Python 多线程与共享变量

c++ - 从 cpp 文件中查找和替换行

c++ - 如何在不破坏现有代码的情况下向函数添加输出参数?

C++/OOP 关联模型和数据库