题目:
有一个超级大的int数组要求和,假设有100W,写一个php脚本, 根据当前机器(假设是多核的)cpu的核数,fork出这么多子进程,把数组平分,每个子进程计算其中一部分,并把结果保存到/tmp/子进程pid.txt. 最后父进程汇总并输出求各结果.
思路分析:
使用pcntl扩展提供的pcntl_fork,pcntl_waitpid,posix_getpid等函数实现fork子进程,等待子进程退出,获取当前进程pid等功能。
代码实现:
<?php $count = 8; $arr = []; $max = 1000000; for($i = 0; $i < $max; $i++){ $arr[$i] = $i; } function sum(&$a,$s,$e){ $pid = posix_getpid(); $sum = 0; while($s <= $e){ $sum += $a[$s++]; } file_put_contents("/tmp/{$pid}.txt",$sum); return $sum; } $step = $max/$count; $s = 0; $children = []; for($j = 0; $j < $count; $j++){ $pid = pcntl_fork(); $e = ($j == $count-1) ? $max-1 : $s+$step-1; if($pid == -1){ echo "fork error\n"; }elseif($pid == 0){ $res = sum($arr,$s,$e); echo posix_getpid(),": ",$s,"--",$e,"=",$res,"\n"; exit; }else{ $s = $e + 1; $children[] = $pid; } } $status = null; $sum = 0; while(count($children) > 0){ $pid = array_shift($children); pcntl_waitpid($pid,$status); $sum = $sum + intval(file_get_contents("/tmp/{$pid}.txt")); } echo "sum=$sum\n";
执行效果:一定要开启pcntl扩展