题目:有一个超级大的int数组要求和,假设有100W,写一个php脚本, 根据当前机器(假设是多核的)cpu的核数,fork出这么多子进程,把数组平分,每个子进程计算其中一部分,并把结果保存到/tmp/子进程pid.txt. 最后父进程汇总...
题目:
有一个超级大的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扩展
沃梦达教程
本文标题为:PHP练习题:进程
猜你喜欢
- Laravel balde模板文件中判断数据为空方法 2023-08-30
- PHP中PDO事务处理操作示例 2022-10-15
- PHP实现微信支付(jsapi支付)流程步骤详解 2022-10-09
- laravel通用化的CURD的实现 2023-03-17
- PHP仿tp实现mvc框架基本设计思路与实现方法分析 2022-10-18
- php微信公众号开发之秒杀 2022-11-23
- PHP简单实现二维数组的矩阵转置操作示例 2022-10-02
- 用nohup命令实现PHP的多进程 2023-09-02
- laravel实现按月或天或小时统计mysql数据的方法 2023-02-22
- windows下9款一键快速搭建PHP本地运行环境的好工具(含php7.0环境) 2023-09-02
