我对curl_multi()的使用是否仍然是串行的? 如果是这样,我该如何并行化?

我对curl_multi()的使用是否仍然是串行的? 如果是这样,我该如何并行化?

问题描述:

I got a hint from someone today that my curl_multi() code is actually working in serial, when my hope was to parallelize the cURL requests.

Is my code still serial? If so, how I can parallelize?

Here's the relevant code:

  /**
   * Returns the cURL responses given multiple target URLs
   * @param array $targetUrls Array of target URLs for cURL
   *
   * @return array cURL Responses
   */
  private function getCurlMultiResponses($targetUrls)
  {
    // Cache the count
    $count = count($targetUrls);

    // Create the multiple cURL handles
    for($i = 0; $i < $count; $i++) {
      $ch[$i] = curl_init($targetUrls[$i]);
      curl_setopt($ch[$i], CURLOPT_POST, FALSE);
      curl_setopt($ch[$i], CURLOPT_SSL_VERIFYPEER, FALSE);
      curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, TRUE);
    }

    // Initialize the multiple cURL handle
    $mh = curl_multi_init();

    // Add the handles to the curl_multi handle
    for($i = 0; $i < $count; $i++) {
      curl_multi_add_handle($mh, $ch[$i]);
    }

    $running = null;
    // Execute the handles
    do {
      curl_multi_exec($mh, $running);
    } while ($running > 0);

    $responses = array();

    // Remove the handles and return the response
    for($i = 0; $i < $count; $i++) {
      curl_multi_remove_handle($mh, $ch[$i]);

      $responses[$i] = curl_multi_getcontent($ch[$i]);
    }

    // Close the multiple cURL handle
    curl_multi_close($mh);

    return $responses;
  }

我今天得到了一个提示,我的 curl_multi() code>代码实际上是在工作 serial,当我希望并行化cURL请求时。 p>

我的代码是否仍然是串行的? strong>如果是,我如何并行化? p>

以下是相关代码: p>

  / ** 
 *返回给定多个目标URL的cURL响应
 * @param array $ targetUrls目标URL数组 for cURL 
 * 
 * @return数组cURL响应
 * / 
私有函数getCurlMultiResponses($ targetUrls)
 {
 //缓存计数
 $ count = count($ targetUrls); 
 \  n //创建多个cURL句柄
($ i = 0; $ i&lt; $ count; $ i ++){
 $ ch [$ i] = curl_init($ targetUrls [$ i]); 
 curl_setopt  ($ ch [$ i],CURLOPT_POST,FALSE); 
 curl_setopt($ ch [$ i],CURLOPT_SSL_VERIFYPEER,FALSE); 
 curl_setopt($ ch [$ i],CURLOPT_RETURNTRANSFER,TRUE); 
} 
  
 //初始化多个cURL句柄
 $ mh = curl_m  ulti_init(); 
 
 //将句柄添加到curl_multi句柄
为($ i = 0;  $ i&lt;  $计数;  $ i ++){
 curl_multi_add_handle($ mh,$ ch [$ i]); 
} 
 
 $ running = null; 
 //执行句柄
做{
 curl_multi_exec($ mh,$ 运行); 
} while($ running&gt; 0); 
 
 $ answers = array(); 
 
 //删除句柄并返回响应
 for($ i = 0; $ i  &lt; $ count; $ i ++){
 curl_multi_remove_handle($ mh,$ ch [$ i]); 
 
 $ answers [$ i] = curl_multi_getcontent($ ch [$ i]); 
} 
  
 //关闭多个cURL句柄
 curl_multi_close($ mh); 
 
返回$ answers; 
} 
  code>  pre> 
  div>

The manual certainly suggests it's a parallel operation:

Allows the processing of multiple cURL handles in parallel.

There's a good tutorial here.