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";
  • 相关阅读:
    Docker网络简介
    Dockerfile数据管理
    Dockerfile指令详解下
    Dockerfile指令详解上
    设计模式之装饰器模式
    设计模式之适配器模式
    Java NIO的工作方式
    使用Dockerfile定制镜像
    jquery+asp.net 调用百度geocoder手机浏览器定位--Api介绍及Html定位方法
    js 取父级 页面上的元素
  • 原文地址:https://www.cnblogs.com/hifelix/p/6509900.html
Copyright © 2011-2022 走看看