首页 > php curl_multi_exec 官网例子里面为啥有两次 do while

php curl_multi_exec 官网例子里面为啥有两次 do while

感觉很难用啊,且这个例子在5.5下还跑不通(下面的 User Contributed Notes 里有人提供了解决方案)

<?php
// 创建一对cURL资源
$ch1 = curl_init();
$ch2 = curl_init();

// 设置URL和相应的选项
curl_setopt($ch1, CURLOPT_URL, "http://lxr.php.net/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);

// 创建批处理cURL句柄
$mh = curl_multi_init();

// 增加2个句柄
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

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

// 关闭全部句柄
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

其中这一部分,谁能帮忙解释一下,用法也太怪了吧!

do {
    $mrc = curl_multi_exec($mh, $active);//位置1
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active && $mrc == CURLM_OK) {
    if (curl_multi_select($mh) != -1) {
        do {
            $mrc = curl_multi_exec($mh, $active);//位置2
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
    }
}

官网对 curl_multi_select 的解释:“阻塞直到cURL批处理连接中有活动连接。”没有事件机制所以不断循环去判断是否不等于-1?!判断成功之后,为啥又执行了一次$mrc = curl_multi_exec($mh, $active);//位置2

这个写法好奇怪啊,有三个while...

User Contributed Notes 里面有人提出如下代码,测试发现可以跑通,但是为啥要循环执行curl_multi_exec,按理说这个方法不是执行一次就好了么...

do {
    curl_multi_exec($mh, $running);
    curl_multi_select($mh);
} while ($running > 0);

效率不同。
官方的demo通过

do {
    $mrc = curl_multi_exec($mh, $active);//位置1
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

去循环,去确保所有进程都被开始执行了。
然后进入第二个嵌套循环。循环去获取还没返回完数据的进程。直到所有的都完成了。

do {
    curl_multi_exec($mh, $running);
    curl_multi_select($mh);
} while ($running > 0);

肯定是可以执行的,只不过你这种如果有一个进程超时,或者很慢,每次循环会拉所有进程一次的,内存和cpu的开销自然很大。。

实现方式不唯一。还有很多人优化到极致的,都可以试试,要根据自己代码的逻辑和业务情况去判断。要怎么优化

【热门文章】
【热门文章】