php的swoole的协程 swoole coroutine

613次阅读
没有评论

共计 808 个字符,预计需要花费 3 分钟才能阅读完成。

$start_time = microtime(true);
$workers = [];
$urls = [
    'https://heidou.store',
    'https://sucai123.com.cn',
    'https://www.baidu.com',
    'https://www.qq.com',

];

## 同步执行,需要4秒
//crawl($urls); 
## 协程方案,执行只需要1秒
process($urls);

$end_time = microtime(true);
echo "time_cost: " . intval($end_time - $start_time) . " s" . PHP_EOL;

function crawl($urls)
{
    foreach ($urls as $url) {
    if (getContent($url)) {
            echo $url.PHP_EOL;
        }
    }

}

function process($urls)
{
    for ($i = 0; $i < count($urls); $i++) {
    // 子进程,总共只需要 1s
    $process = new \Swoole\Process(function (\Swoole\Process $worker) use ($i, $urls) {
            // curl
            $content = getContent($urls[$i]);
            $worker->write($content); //把数据写入管道
        }, false);
        $pid = $process->start();
        $workers[$pid] = $process;
    }

    foreach ($workers as $process) {
        $str = $process->read(); //从管道中读取数据
        var_dump($str);
    }
    \Swoole\Process::wait();
}

function getContent ($url)
{
    sleep(1);
    //file_get_contents($url);
    return $url;
}
正文完
 1
BlackBeans
版权声明:本站原创文章,由 BlackBeans 2023-10-07发表,共计808字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。