进程(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进程在系统是非常昂贵的资源,创建进程消耗很大。另外创建的进程过多会导致进程切换开销大幅上升。