zoukankan      html  css  js  c++  java
  • 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
    ";
        }elseif($pid == 0){
            $res = sum($arr,$s,$e);
            echo posix_getpid(),": ",$s,"--",$e,"=",$res,"
    ";
            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
    ";

    执行效果:一定要开启pcntl扩展

  • 相关阅读:
    [Java IO]04_系统标准IO
    [Java IO]03_字符流
    [Java IO]02_字节流
    [Java IO]01_File类和RandomAccessFile类
    [Java 安全]加密算法
    [Java 安全]消息摘要与数字签名
    Java正则速成秘籍(三)之见招拆招篇
    Java正则速成秘籍(一)之招式篇
    Java 枚举
    redis 系列13 集合对象
  • 原文地址:https://www.cnblogs.com/ling-diary/p/10605822.html
Copyright © 2011-2022 走看看