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";
  • 相关阅读:
    acm入门 杭电1001题 有关溢出的考虑
    面向对象课后深入学习(C++ 类的静态成员详细讲解)
    Eclipse中导入项目后js报错解决方法
    mysql用户链接数
    配置服务器nginx 教程
    eclipse如何新建项目发布到git
    获取当天开始时间结束时间
    pdf在线加载·
    springmvc配置详解 教程
    hibulder中使用git教程
  • 原文地址:https://www.cnblogs.com/hifelix/p/6509900.html
Copyright © 2011-2022 走看看