php 多进程处理

来源:互联网 发布:阿萨辛捏脸数据 编辑:程序博客网 时间:2024/06/07 04:03
<?php
/**
* @copyright nidongde
* @author fanyijie
**/
class ProcessPool{    private $workProcess;    private $globalProcessSize;    private $currentSize;    public function __construct($size = 5)    {        declare(ticks = 1);        $this->workProcess = array();        $this->globalProcessSize = $size;        $this->currentSize = 0;        pcntl_signal(SIGCHLD,array(&$this,"childFinished"));    }    private function childFinished(){        while($pid = pcntl_waitpid(-1, $status, WNOHANG) > 0 ){            echo 'child finished '.$pid."\n";            unset($this->workProcess[$pid]);            $this->currentSize--;        }    }    public function addMission($object, $method, $params)    {
//若存在db等资源共享情况,建议重新生成object        $class = get_class($object);        $reflectClass = new ReflectionClass($class);        $methods = $reflectClass->getMethods();        $methodFunction = null;        foreach($methods as $reflectMethod){            if($reflectMethod->getName() == $method){                $methodFunction = $reflectMethod;                break;            }        }        if (!empty($methodFunction)) {            while ($this->currentSize >= $this->globalProcessSize) {                sleep(1);            }            $pid = pcntl_fork();            if ($pid == 0) {                $ret = $methodFunction->invoke($object, $params);                //子进程结束                echo $ret." pid :".getmypid();                exit(0);            } else {                $this->currentSize++;                $this->workProcess[] = $pid;            }        }    }}
0 0
原创粉丝点击