脚本宝典收集整理的这篇文章主要介绍了分享PHP-pcntl 实现多进程代码,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
PHP使用pcntl系列的函数也能做到多进程处理一个事务。比如我需要从数据库中获取80w条的数据,再做一系列后续的处理,这个时候,用单进程?你可以等到明年今天了。。。所以应该使用pcntl函数了。
下面我们来看个实例
<PRe class="brush:PHp;"> <>PHP $ArchildId = array();for($i = 0; $i < 10; $i++)
{
$iPid = pcntl_fork();
if($iPid == -1)
{
die('can\'t be forked.');
}
if($iPid)
{
$arChildId[] = $iPid;
}
else
{
$iPid = posix_getpid(); # 获取子进程的ID
$iSeconds = rand(5,30);
echo '* Process '. $iPid. ' was created,and Executed,and Sleep '. $iSeconds. PHP_EOL;
excuteProcess($iPid,$iSeconds);
exIT();
}
}
while(count($arChildId) > 0)
{
foreach($arChildId as $iKey=> $iPid)
{
$res = pcntl_waitpid($iPid,$status,WNOHANG);
if($res == -1 || $res > 0)
{
unset($arChildId[$iKey]);
echo '* Sub process: '. $iPid. ' exited with '. $status. PHP_EOL;
}
}
}
function excuteProcess($iPid,$iSeconds)
{
file_put_contents('./LOG/'.$iPid.'.log',$iPid.PHP_EOL,FILE_APPEND);
sleep($iSeconds);
}
?>
以上是脚本宝典为你收集整理的分享PHP-pcntl 实现多进程代码全部内容,希望文章能够帮你解决分享PHP-pcntl 实现多进程代码所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。