首页 > 文章列表 > 如何用curl_multi_init将单线程CURL请求改写成多线程版本以提升效率?

如何用curl_multi_init将单线程CURL请求改写成多线程版本以提升效率?

456 2025-01-28

如何用curl_multi_init将单线程CURL请求改写成多线程版本以提升效率?

curl_multi_init单线程改多线程

问题:
如何将以下单线程curl代码改写成多线程版本,利用curl_multi_init提高效率?

for ($i=0; $i < 100; $i++) {
    $res[$key] = post($url, 'key='.$i);
}

答案:

以下是使用curl_multi_init实现多线程版本的代码:

$newData = array_chunk($data, 10, true);
foreach ($newData as $k => $tmp) {
    $mh = curl_multi_init();
    $chs = [];
    foreach ($tmp as $key => $url) {
        $ch = curl_init();
        $chs[$key] = $ch;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type:application/x-www-form-urlencoded;charset=utf-8;'));
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $tmp);
        curl_multi_add_handle($mh, $ch);
    }
    $active = null;
    do {
        $mrc = curl_multi_exec($mh, $active);
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);
    while ($active && $mrc == CURLM_OK) {
        if (curl_multi_select($mh) != -1) {
            do {
                $mrc = curl_multi_exec($mh, $active);
            } while ($mrc == CURLM_CALL_MULTI_PERFORM);
        }
    }
    foreach ($chs as $key => $ch) {
        $res[$k][$key] = curl_multi_getcontent($ch);
        curl_multi_remove_handle($mh, $ch);
    }

    curl_multi_close($mh);
}

相对于单线程版本,此代码通过curl_multi_init同时执行多个curl请求,并使用curl_multi_exec等函数控制这些请求的执行流程,从而提高了效率。

来源:1733022025