206.217. 207. 212,津巴布韦用大象抵债,bml050
php使用pcntl系列的函数也能做到多进程处理一个事务。比如我需要从数据库中获取80w条的数据,再做一系列后续的处理,这个时候,用单进程?你可以等到明年今天了。。。所以应该使用pcntl函数了。
下面我们来看个实例
代码
<?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); } ?>
运行结果
* process 16163 was created, and executed, and sleep 11 * process 16164 was created, and executed, and sleep 21 * process 16165 was created, and executed, and sleep 24 * process 16166 was created, and executed, and sleep 27 * process 16167 was created, and executed, and sleep 8 * process 16168 was created, and executed, and sleep 14 * process 16169 was created, and executed, and sleep 14 * process 16170 was created, and executed, and sleep 26 * process 16171 was created, and executed, and sleep 20 * process 16172 was created, and executed, and sleep 21 * sub process: 16167 exited with 0 * sub process: 16163 exited with 0 * sub process: 16169 exited with 0 * sub process: 16168 exited with 0 * sub process: 16171 exited with 0 * sub process: 16164 exited with 0 * sub process: 16172 exited with 0 * sub process: 16165 exited with 0 * sub process: 16170 exited with 0 * sub process: 16166 exited with 0
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
PHP date_default_timezone_set()设置时区操作实例分析
网友评论