PHP中的进程数组并行使用pcntl_fork()

时间:2017-11-06 12:53:02

标签: php arrays fork pcntl

我正在尝试完成一项任务,我需要在将其分解成块之后并行处理字符串数组。

我有一个大小为3000的数组,我需要将其分解为多个大小为100的数组。

我使用以下方式实现了它:

$chunks = array_chunk($keywords,100); // $keywords is my array of size 3000  

现在我有一个名为process的方法,我需要处理每个块(较小的数组大小为100)。

public function process($chunk){
    foreach($chunk as $keyword){
        // Process the single keyword...
    }
}  

但上述任务是以每个块并行处理的方式实现的...... 我的整个脚本是:

<?php
    public function readKeywords(){
        $keywords = array();

        // code to read a file and populate the array $keywords

        return $keywords;
    }

    public function process($chunk){
        foreach($chunk as $keyword){
            // Process the single keyword...
        }
    } 

    public function init($chunks,$index = 0){
        $pid = pcntl_fork();

        if($pid === -1){
            // Couldn't fork
        } else if($pid){
            process($chunks[$index]);
        }else{
            $index++;
            if(count($chunks) > $index){
                 process($chunks,$index);
            }
        }
    }

    public function start($keywords){
        $chunks = array_chunk($keywords,100);
        init($chunks);
    }


    $keywords = readKeywords();
    start($keywords);
?>  

现在的挑战是,如果我在阵列中有3000个关键字,并且如果我以100块的形式将其分解,我将有30个活动进程来处理每个块。

因此,当pause进程处于活动状态时,我需要3创建块。如果任何1进程的3完成,则应再次发生递归,并且应创建新的子进程并处理下一个进程块。这会增加执行时间,但没关系。

因此,为了限制进程数量,我尝试了以下代码,但没有运气:

public void init($chunks){
    $pids = array();

    for($i = 0;$i < 3;$i++){
        $pid = pcntl_fork();  
        if($pid === -1){
             // Couldn't fork
        } else if($pid){
            process($chunks[$i]);
        }else{
            exit();
        }
    }

    for($i = 0;$i < count($pids);$i++){
        pcntl_waitpid($pids[$i],$status,WUNTRACED); // Read somewhere that it waits  till it's child process has completed execution
    }

    if($index < count($chunks)) // If there are chunks remaining to be processed {
        $newChunks = array();
        for($i = 3;$i < count($chunks);$i++){
            $newChunks[] = $chunks[$i];
        }
        init($newChunks);
    }
}  

一直在努力,但没有运气。请帮忙。

1 个答案:

答案 0 :(得分:0)

尝试exec('ps -C '.$filename, $processes);之类的内容,然后计算$processes以检查其中有多少正在运行