题目:有一个超级大的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练习题:进程


基础教程推荐
猜你喜欢
- thinkPHP3.2.2框架行为扩展及demo示例 2022-11-07
- php中使用array_filter()函数过滤数组实例讲解 2023-05-19
- PHP实现生成数据字典功能示例 2022-10-18
- PHP使用SMTP邮件服务器发送邮件示例 2022-11-16
- laravel model模型定义实现开启自动管理时间created_at,updated_at 2023-03-02
- PHP删除数组中指定值的元素常用方法实例分析【4种方法】 2022-11-12
- TP5 连接多个数据库及使用方法 2023-08-30
- PHP数据加密方式梳理介绍 2023-07-03
- TP5(thinkPHP5框架)基于bootstrap实现的单图上传插件用法示例 2023-01-19
- PHP实现创建一个RPC服务操作示例 2023-04-01