php curl机制,php curl multi 并发请求用法与原理

$mh = curl_multi_init();

foreach($chs as $k => $ch){

curl_multi_add_handle($mh, $ch);

}

// 注意以下代码在 libcurl < 7.20.0 运行良好,升级 libcurl 版本 >= 7.20.0 需要做调整、测试、开发

// https://curl.haxx.se/libcurl/c/libcurl-errors.html

// Before version 7.20.0 this could be returned by curl_multi_perform, but in later versions this return code is never used.

$active = null;

do {

$mrc = curl_multi_exec($mh, $active);

if ($mrc > 0) throw new Exception(curl_multi_strerror($mrc));

} while ($mrc == CURLM_CALL_MULTI_PERFORM);

// https://bugs.php.net/bug.php?id=61141:

// amoo_miki at yahoo dot com

while ($active && $mrc == CURLM_OK) {

if (curl_multi_select($mh) == -1) {

usleep(100);

}

do {

$mrc = curl_multi_exec($mh, $active);

if ($mrc > 0) throw new Exception(curl_multi_strerror($mrc));

} while ($mrc == CURLM_CALL_MULTI_PERFORM);

}

$result = [];

foreach($chs as $k => $ch){

$result[$k] = curl_multi_getcontent($ch);

curl_multi_remove_handle($mh, $ch);

}

curl_multi_close($mh);

我的理解

以上是使用 curl multi 示例,总的来说,这个用法让人感到很疑惑。

特别是 usleep(100) 部分,pierrick@php.net 回复了这块原因:When max_fd returns with -1, you need to wait a while and then

proceed and call curl_multi_perform anyway. How long to wait? I would suggest

100 milliseconds at least, but you may want to test it out in your own

particular conditions to find a suitable value.

关于 curl multi 的并发原理,通过查阅资料,记录一下我的理解:

curl_muti_* 函数族,调用 libcurl-multi 相关 API,利用 select I/O 多路复用机制,实现并发请求。

参考资料

1.Doc Bug #61141 curl_multi_select returns -1

https://bugs.php.net/bug.php?id=61141

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值