swoole中的进程

进程(process):
swoole_process目的在于使PHP在多进程编程方面更加轻松。我们可以使用进程来处理许多耗时的场景,比如:curl多个页面内容

传统的方式:

$url = [
    'http://test1.com',
    'http://test6.com',
    'http://test5.com',
    'http://test4.com',
    'http://test3.com',
    'http://test2.com',
];



foreach ($url as $key => $value) {
    //同步顺序执行,耗时每个file_get_contents相加。
    $contents[] = file_get_contents($value);
}

process方式:

echo 'process-start:'.date('Ymd H:i:s',time()).PHP_EOL;
$url = [
    'http://test1.com',
    'http://test6.com',
    'http://test5.com',
    'http://test4.com',
    'http://test3.com',
    'http://test2.com',
];

$workers = [];

for ($i=0; $i < 6; $i++) { 
    //进程内执行,耗时取子进程总耗时最长的一个
    $process = new swoole_process(function(swoole_process $worker) use($i,$url){
        $con = getCurl($url[$i]);
        $worker->write($con);
    },true);
    $pid = $process->start();
    $workers[$pid] = $process;
}

function getCurl($url){
    sleep(1);

    return $url.PHP_EOL;
}

foreach ($workers as $key => $value) {
    echo $value->read();
}

echo 'process-end:'.date('Ymd H:i:s',time()).PHP_EOL;

结果:总耗时一秒

➜  process git:(master) ✗ php curl.php
process-start:20190321 08:24:12
http://test1.com
http://test6.com
http://test5.com
http://test4.com
http://test3.com
http://test2.com
process-end:20190321 08:24:13

总结:原生PHP处理这种情况通常是master主进程单独处理,master进程是阻塞的,所以是顺序执行程序。而swoole_process通过创建一个主进程,主进程中创建多个子进程来执行程序,所以执行速度比原生的顺序执行快很多。这就好比一个人干同一件事情,和交由多个人干一件事情,自己只负责管理监督。我们可以交由子进程来处理一些耗时的程序,需要注意Process进程在系统是非常昂贵的资源,创建进程消耗很大。另外创建的进程过多会导致进程切换开销大幅上升。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容