码迷,mamicode.com
首页 > 系统相关 > 详细

使用swoole多进程案例[管道通讯]

时间:2020-05-16 17:06:25      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:image   http   管道   echo   read   之间   event   img   bsp   

1.管道通讯

技术图片

 

 

<?php
    class BaseProcess{
        private $process;
        public function __construct(){
            $this->process = new swoole_process(array($this,run),false,true);
            $this->process->start();

            swoole_event_add($this->process->pipe,function($pipe){
                $data = $this->process->read();
                echo $data.PHP_EOL;
            });
        }

        public function run($worker){
            swoole_timer_tick(1000,function($time_id){
                static $index =0;
                $index= $index+1;
                $this->process->write($index);
                var_dump($index);
                if($index == 10){
                    swoole_timer_clear($time_id);
                }
            });
        }
    }

    for($i=0;$i<2;$i++){
        new BaseProcess();
        sleep(1);
    }
    //使用Process作为监控父进程,创建管理子进程时,父类必须注册信号SIGCHLD对退出的进程执行wait操作
    swoole_process::signal(SIGCHLD,function($sig){
        while($ret = swoole_process::wait(false)){
            echo "PID={$ret[‘pid‘]}".PHP_EOL;
        }
    });
?>

 2.消息队列

技术图片

 

 

#swoole使用消息队列实现进程之间的通讯
    class BaseProcess{
        private $process;
        public function __construct(){
            $this->process = new swoole_process(array($this,run),false,true);
            if(!$this->process->useQueue(123)){
                var_dump(swoole_strerror(swoole_errno()));
                exit;
            }
            $this->process->start();
            while(true){
                $data = $this->process->pop();
                echo $data.PHP_EOL;
            }
        }

        public function run(){
            swoole_timer_tick(1000,function($timer_id){
                static $index=0;
                $index = $index+1;
                $this->process->push("hello");
                if($index==10){
                    swoole_timer_clear($timer_id);
                }
            });
        }
    }
    new BaseProcess();
    swoole_process::signal(SIGCHLD,function($sig){
        while($ret = swoole_process::wait(false)){
            $pid = $ret[pid];
            echo "pid = $pid";
        }
    });

 

使用swoole多进程案例[管道通讯]

标签:image   http   管道   echo   read   之间   event   img   bsp   

原文地址:https://www.cnblogs.com/zh718594493/p/12900928.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!