当前位置: 首页 > 后端技术 > PHP

PHP多进程处理任务

时间:2023-03-29 20:35:12 PHP

PHP多进程处理任务pcntl模块(非Unix系统不支持该模块)PHP多进程处理的简单例子如下://5个子进程处理任务为($i=0;$i<5;$i++){$pid=pcntl_fork();if($pid==-1){die("无法分叉");}elseif($pid){echo"我是父$i\n";}else{//子进程处理echo"I'mtheChild$i\n";//业务处理exit($i);//一定要注意退出子进程,否则pcntl_fork()会fork被子进程,对处理带来影响。}}//等待子进程完成while(pcntl_waitpid(0,$status)!=-1){$status=pcntl_wexitstatus($status);echo"Child$statuscompleted\n";}当然,我们不能这样输出代码,不够健壮,也不够优雅,于是找了一个基于pcntl打包的扩展包来使用。spatie/async-基于pcntl封装的扩展包下面是我用spatie/async优化一个多进程请求的例子原代码(耗时20s左右)-https://github.com/guanguans/。..:/***@paramstring$keyword**@returnarray*/publicfunctionsearchAll(string$keyword):array{$songAll=[];foreach($this->platformsas$platform){$songAll=array_merge($songAll,$this->search($platform,$keyword));}}return$songAll;}/***@paramstring$platform*@paramstring$keyword**@returnmixed*/publicfunctionsearch(string$platform,string$keyword){$meting=$this->getMeting($平台);$songs=json_decode($meting->format()->search($keyword),true);foreach($songsas$key=>&$song){$detail=json_decode($meting->format()->url($song['url_id']),true);if(empty($detail['url'])){unset($songs[$key]);}$song=array_merge($song,$detail);}未设置($歌曲);return$songs;}改进后(大约需要4s)-https://github.com/guanguans/...:/***@paramstring$keyword**@returnarray*/publicfunctionsearchAll(string$keyword):array{$songAll=[];$pool=池::创建();foreach($this->platformsas$platform){$pool->add(function()use($platform,$keyword){return$this->search($platform,$keyword);},$this->复制代码getSerializedOutput())->then(function($output)使用(&$songAll){$songAll=array_merge($songAll,$output);})->catch(function(\Throwable$exception){exit($exception->getMessage());});}$池->等待();return$songAll;}/***@returnmixed*/publicfunctionsearch(string$platform,string$keyword){$meting=$this->getMeting($platform);}$songs=json_decode($meting->format()->search($keyword),true);$pool=池::创建();foreach($songsas$key=>&$song){$pool->add(function()使用($meting,$song){返回json_decode($meting->format()->url($song['url_id']),true);})->then(函数($output)使用(&$songs,&$song,$key){$song=array_merge($song,$output);if(empty($song['url'])){unset($songs[$key]);}})->catch(function(\Throwable$exception){exit($exception->getMessage());});}未设置($歌曲);$池->等待();return$songs;}相关链接https://www.php.net/manual/zh/book.pcntl.phphttps://github.com/spatie/asynchttps://github.com/guanguans/music-php原文链接https://github.com/guanguans/guanguans.github.io