PHP練習題:進程

題目php

有一個超級大的int數組要求和,假設有100W,寫一個php腳本, 根據當前機器(假設是多核的)cpu的核數,fork出這麼多子進程,把數組平分,每一個子進程計算其中一部分,並把結果保存到/tmp/子進程pid.txt. 最後父進程彙總並輸出求各結果.數組

思路分析:函數

使用pcntl擴展提供的pcntl_fork,pcntl_waitpid,posix_getpid等函數實現fork子進程,等待子進程退出,獲取當前進程pid等功能。spa

代碼實現:code

<?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擴展blog

相關文章
相關標籤/搜索