PHP练习题:进程

题目

有一个超级大的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扩展

转载于:https://www.cnblogs.com/ling-diary/p/10605822.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值