完美实现PHP多线程

通过pcntl实现PHP多线程

<?php

/**
 * Class Test
 */
class Test {public $maxCore;

    public $parentProcess;
    /**
     * Test constructor.
     */
    public function __construct($maxCore) {
        $this->maxCore = $maxCore;
    }

    /**
     *
     */
    public function execute() {
        $config = array(
            array('A', 10),
            array('B', 5),
            array('C', 10),
            array('D', 10),
            array('E', 10),
            array('F', 2),
        );
        foreach($config as $item) {
            $this->childProcess($item[0], $item[1]);
        }
        while(count($this->parentProcess)) {
            $pid = pcntl_waitpid(-1, $status, WNOHANG);
            if(0 === $pid)
            {
                sleep(1);
            }
            else
            {
                if(0 !== pcntl_wexitstatus($status))
                {
                    $success = false;
                }
                unset($this->parentProcess[$pid]);
            }
        }
        echo "success";
    }

    /**
     * @param $type
     * @param $config
     */
    public function childTask($type, $config) {
        sleep($config);
        echo $type . " done
";
    }

    /**
     * @param $type
     * @param $config
     */
    public function childProcess($type, $config) {
        //超过数量则阻塞等待子进程结束
        if (count($this->parentProcess) >= $this->maxCore) {
            $childPid = pcntl_wait($status);
            if ($childPid <= 0) {
                exit();
            }

            if ($status == SIGTERM) {
                unset($this->parentProcess[$childPid]);
            }
        }
        $pid = pcntl_fork();
        if($pid == -1) {
            echo "error";
            die;
        }
        else if ($pid > 0) {
            echo "parents;
";
            $this->parentProcess[$pid] = 1;
        }
        else {
            $this->childTask($type, $config);
            posix_kill(posix_getpid(), SIGTERM);
            exit(0);
        }
    }
}
$startTime = time();
$t = new Test(2);
$t->execute();
$endTime = time();
echo "cost " . ($endTime - $startTime) . " s";
原文地址:https://www.cnblogs.com/hifelix/p/6509900.html