pcntl
模块(非 Unix 类系统不支持此模块)
一个 PHP 多进程简单例子大概是这个样子:
// 5 个子进程处理任务for ($i = 0; $i < 5; $i++) { $pid = pcntl_fork(); if ($pid == -1) { die("could not fork"); } elseif ($pid) { echo "I'm the Parent $i\n"; } else { // 子进程处理 echo "I'm the Child $i\n"; // 业务处理 exit($i); // 一定要注意退出子进程,否则 pcntl_fork() 会被子进程再 fork,带来处理上的影响。 } }// 等待子进程执行结束while (pcntl_waitpid(0, $status) != -1) { $status = pcntl_wexitstatus($status); echo "Child $status completed\n"; }复制代码
当然实际应用中我们不能够这样输出代码,不够健壮,也不够优雅,我所以找了个基于 pcntl
封装的扩展包来使用。
spatie/async - 基于 pcntl
封装的扩展包
以下是我使用 spatie/async
来优化一个多进程请求的例子
原代码(耗时 20s 左右)- github.com/guanguans/m…
/** * @param string $keyword * * @return array */public function searchAll(string $keyword): array{ $songAll = []; foreach ($this->platforms as $platform) { $songAll = array_merge($songAll, $this->search($platform, $keyword)); } return $songAll; }/** * @param string $platform * @param string $keyword * * @return mixed */public function search(string $platform, string $keyword){ $meting = $this->getMeting($platform); $songs = json_decode($meting->format()->search($keyword), true); foreach ($songs as $key => &$song) { $detail = json_decode($meting->format()->url($song['url_id']), true); if (empty($detail['url'])) { unset($songs[$key]); } $song = array_merge($song, $detail); } unset($song); return $songs; }复制代码
改进后(耗时 4s 左右)- github.com/guanguans/m…
/** * @param string $keyword * * @return array */public function searchAll(string $keyword): array{ $songAll = []; $pool = Pool::create(); foreach ($this->platforms as $platform) { $pool->add(function () use ($platform, $keyword) { return $this->search($platform, $keyword); }, $this->getSerializedOutput())->then(function ($output) use (&$songAll) { $songAll = array_merge($songAll, $output); })->catch(function (\Throwable $exception) { exit($exception->getMessage()); }); } $pool->wait(); return $songAll; }/** * @return mixed */public function search(string $platform, string $keyword){ $meting = $this->getMeting($platform); $songs = json_decode($meting->format()->search($keyword), true); $pool = Pool::create(); foreach ($songs as $key => &$song) { $pool->add(function () use ($meting, $song) { return json_decode($meting->format()->url($song['url_id']), true); })->then(function ($output) use (&$songs, &$song, $key) { $song = array_merge($song, $output); if (empty($song['url'])) { unset($songs[$key]); } })->catch(function (\Throwable $exception) { exit($exception->getMessage()); }); } unset($song); $pool->wait(); return $songs; }复制代码
想了解更多编程学习,敬请关注php培训栏目!
以上是看看PHP 多进程处理任务的详细内容。更多信息请关注PHP中文网其他相关文章!

tomakephpapplicationsfaster,关注台词:1)useopcodeCachingLikeLikeLikeLikeLikePachetoStorePreciledScompiledScriptbyTecode.2)MinimimiedAtabaseSqueriSegrieSqueriSegeriSybysequeryCachingandeffeftExting.3)Leveragephp7 leveragephp7 leveragephp7 leveragephpphp7功能forbettercodeefficy.4)

到ImprovephPapplicationspeed,关注台词:1)启用opcodeCachingwithapCutoredUcescriptexecutiontime.2)实现databasequerycachingusingpdotominiminimizedatabasehits.3)usehttp/2tomultiplexrequlexrequestsandredececonnection.4 limitsclection.4.4

依赖注入(DI)通过显式传递依赖关系,显着提升了PHP代码的可测试性。 1)DI解耦类与具体实现,使测试和维护更灵活。 2)三种类型中,构造函数注入明确表达依赖,保持状态一致。 3)使用DI容器管理复杂依赖,提升代码质量和开发效率。

databasequeryOptimizationinphpinvolVolVOLVESEVERSEVERSTRATEMIESOENHANCEPERANCE.1)SELECTONLYNLYNESSERSAYCOLUMNSTORMONTOUMTOUNSOUDSATATATATATATATATATATRANSFER.3)

phpisusedforsenderemailsduetoitsbuilt-inmail()函数andsupportiveLibrariesLikePhpMailerandSwiftMailer.1)usethemail()functionforbasicemails,butithasimails.2)butithasimimitations.2)

PHP性能瓶颈可以通过以下步骤解决:1)使用Xdebug或Blackfire进行性能分析,找出问题所在;2)优化数据库查询并使用缓存,如APCu;3)使用array_filter等高效函数优化数组操作;4)配置OPcache进行字节码缓存;5)优化前端,如减少HTTP请求和优化图片;6)持续监控和优化性能。通过这些方法,可以显着提升PHP应用的性能。

依赖性注射(DI)InphpisadesignPatternthatManages和ReducesClassDeptions,增强量产生性,可验证性和Maintainability.itallowspasspassingDepentenciesLikEdenceSeconnectionSeconnectionStoclasseconnectionStoclasseSasasasasareTers,interitationApertatingAeseritatingEaseTestingEasingEaseTeStingEasingAndScalability。

cachingimprovesphpermenceByStorcyResultSofComputationsorqucrouctationsorquctationsorquickretrieval,reducingServerLoadAndenHancingResponsetimes.feftectivestrategiesinclude:1)opcodecaching,whereStoresCompiledSinmememorytssinmemorytoskipcompliation; 2)datacaching datacachingsingMemccachingmcachingmcachings


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

WebStorm Mac版
好用的JavaScript开发工具

SublimeText3汉化版
中文版,非常好用

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具