curl_multi_init单线程改多线程实现

原来单线程的curl实现如下:

function post($url, $data = '', $head = 'application/x-www-form-urlencoded')
{
    // ...
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}
登录后复制

现在要将其改为多线程,思路是将数据数组分成小块,然后对每一块都创建一个单独的curl句柄。

$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_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);
}

var_dump($res);
登录后复制

以上就是如何将单线程的curl_multi_init改造成多线程并发请求?的详细内容,更多请关注慧达安全导航其它相关文章!

点赞(0)

评论列表 共有 0 条评论

暂无评论
立即
投稿
发表
评论
返回
顶部