zoukankan      html  css  js  c++  java
  • 完美实现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";
  • 相关阅读:
    BZOJ1999或洛谷1099&BZOJ2282或洛谷2491 树网的核&[SDOI2011]消防
    BZOJ1912或洛谷3629 [APIO2010]巡逻
    CH6202 黑暗城堡
    POJ2728 Desert King
    JoyOI1391 走廊泼水节
    洛谷1073 最优贸易
    POJ3662或洛谷1948 Telephone Lines
    BZOJ1106 [POI2007]立方体大作战tet
    ubuntu 16.04 安装genymotion
    ubuntu下搭建android开发环境核心篇安装AndroidStudio、sdk、jdk
  • 原文地址:https://www.cnblogs.com/hifelix/p/6509900.html
Copyright © 2011-2022 走看看