如何通过php pcntl将数据从子进程传递到主进程?

时间:2015-07-29 01:36:57

标签: php pcntl

我启动一些pcntl进程来计算一些数据,我想等所有子进程结束,并将所有返回数据发送到主进程。

我该怎么做?

我的pnctl特征是这样的:

<?php namespace App\Console\Commands;

trait PcntlTrait
{
    private $workers = 1;

    public function worker($count)
    {
        $this->worker = $count;
    }

    public function pcntl_call($all, \Closure $callback)
    {
        $count = count($all);
        $perNum = ceil($count / $this->workers);

        for($i = 0; $i < $this->workers; $i++){
            $pids[$i] = pcntl_fork();
            switch ($pids[$i]) {
                case -1:
                    echo "fork error : {$i} \r\n";
                    exit;
                case 0:
                    $start = $i * $perNum;
                    return $callback(array_slice($all, $start, $perNum));
                    exit;
                default:
                    break;
            }
        }

        $ret = [];
        foreach ($pids as $i => $pid) {
            if($pid) {
                pcntl_waitpid($pid, $info);
                $ret = array_merge($ret, $info);
            }
        }

        return $ret;
    }
}

和我的TestCase一样:

<?php

use App\Console\Commands\PcntlTrait;

class PcntlImp
{
        use PcntlTrait;
}

class TestPcntlTrait extends \TestCase
{
    public function setup()
    {
        $this->createApplication();
    }

    public function testPcntlCall()
    {
        $arr = [1,2,3,4,5,6,7,8,9,10];

        $imp = new \PcntlImp();
        $imp->worker(1);

        $data = $imp->pcntl_call($arr, function($info){
            if (empty($info)){
                return [];
            }

            $ret = [];
            foreach ($info as $item) {
                $ret[] = $item * $item;
            }
            return $ret;
        });

        $this->assertCount(10, $data);
    }
}

但我可以得到错误:

array_merge(): Argument #2 is not an array

我知道pcntl_wait函数的第二个参数是状态而不是返回数据。但我不知道该怎么办?

0 个答案:

没有答案
相关问题