使用swoole多进程案例[管道通讯]
Posted 一株草
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用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"; } });
以上是关于使用swoole多进程案例[管道通讯]的主要内容,如果未能解决你的问题,请参考以下文章