永发信息网

PHP-php 怎么实现类似多线程

答案:1  悬赏:50  手机版
解决时间 2021-04-27 19:41
  • 提问者网友:川水往事
  • 2021-04-27 08:46
PHP-php 怎么实现类似多线程
最佳答案
  • 五星知识达人网友:一把行者刀
  • 2021-04-27 10:08
php本身不支持多线程,但可以通过curl_multi_*系列函数来模拟多线程,以下是我用过的一个函数,但请求不能过多,否则会出现一些难以解释的问题。希望对你有帮助。

function rolling_curl($urls, $delay) {
$queue = curl_multi_init();
$map = array();

foreach ($urls as $url) {
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_NOSIGNAL, true);

curl_multi_add_handle($queue, $ch);
$map[(string) $ch] = $url;
}

$responses = array();
do {
while (($code = curl_multi_exec($queue, $active)) == CURLM_CALL_MULTI_PERFORM) ;

if ($code != CURLM_OK) { break; }

// a request was just completed -- find out which one
while ($done = curl_multi_info_read($queue)) {

// get the info and content returned on the request
$info = curl_getinfo($done['handle']);
$error = curl_error($done['handle']);
$results = callback(curl_multi_getcontent($done['handle']), $delay);
$responses[$map[(string) $done['handle']]] = compact('info', 'error', 'results');

// remove the curl handle that just completed
curl_multi_remove_handle($queue, $done['handle']);
curl_close($done['handle']);
}

// Block for data in / output; error handling is done by curl_multi_exec
if ($active > 0) {
curl_multi_select($queue, 0.5);
}

} while ($active);

curl_multi_close($queue);
return $responses;
}

function callback($data, $delay) {
preg_match_all('/(.+)<\/h3>/iU', $data, $matches);
usleep($delay);
return compact('data', 'matches');
}

$urls = array();
for($i=0;$i<5;$i++)
{
array_push($urls,"http://localhost/baiduPush/demo/hello2.php");
}
rolling_curl($urls, 0.5);
?>
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯