zoukankan      html  css  js  c++  java
  • 使用swoole多进程案例【一】

    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";
            }
        });
  • 相关阅读:
    win10自带输入法突然变成了繁体
    Eclipse 包视图折叠
    Unknown column '字段名' in 'field list' 错误解决方案
    The method getContextPath() from the type HttpServletRequest
    Eclipse 设置新建文件默认编码为 utf-8 的方法
    Java 混淆器
    程序员,不能缺少的几张图
    北漂程序员,扬帆起航的地方
    数据是啥?数据都去哪儿了?
    7行代码搞定WEB服务
  • 原文地址:https://www.cnblogs.com/zh718594493/p/12900928.html
Copyright © 2011-2022 走看看