php原生实现多进程同步执行程序代码

使用pcntl扩展


<?php
class WorkerManage{
    protected $count;

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

    protected $callback;

    public function addWorker(callable $callback)
    {
        $this->callback = $callback;
    }

    public function wait()
    {
        $pids = [];
        for($i=0;$i<$this->count;$i++)
        {
            $pids[$i] = pcntl_fork();
            switch ($pids[$i]){
                case -1:
                    throw new \Error('创建进程失败');
                case 0:
                    call_user_func_array(
                        $this->callback,[]
                    );
                    exit;
                default:
                    break;
            }
        }
        foreach ($pids as $i => $pid)
        {
            if ($pid)
            {
                // 这个是在父进程中
                pcntl_waitpid($pid,$status);
            }
        }
    }
}

$manage = new WorkerManage(3);

$manage->addWorker(function (){
    echo(sprintf('start time:[%s]',date('Y-m-d H:i:s'))).PHP_EOL;
    sleep(4);
    echo(sprintf('end time:[%s]',date('Y-m-d H:i:s'))).PHP_EOL;
    return uniqid();
});
echo '任务开启前'.PHP_EOL;
$manage->wait();
echo '任务开启后'.PHP_EOL;


执行结果

总结

可以看到多个任务是同一时间进行的。但是进程之间没办法直接通信,内存都是隔离的。

posted @ 2022-09-16 14:12  Death-Satan  阅读(317)  评论(0编辑  收藏  举报