$workers = [];
$worker_num = 2;
for($i = 0; $i < $worker_num; $i++)
{
$process = new swoole_process('callback_function',false,false);
$process->useQueue();
$pid = $process->start();
$workers[$pid] = $process;
//echo "Master: new worker, PID=".$pid."\n";
}
function callback_function(swoole_process $worker)
{//子进程要处理的逻辑
//echo "Worker: start. PID=".$worker->pid."\n";
//recv data from master
$recv = $worker->pop();//子进程结束从主进程传过来的数据(2)
echo "From Master: $recv\n";
$worker->push(" \n hehe \n ");//这里子进程向主进程发送 hehe(3)
// sleep(2);//注意这里有个sleep
$worker->exit(0);
}
//向子进程通信
foreach($workers as $pid => $process)
{
$process->push("hello worker[$pid]\n");//主进程向子进程发生数据(1)
sleep(3);
$result = $process->pop();//主进程接收从子传过来的数据(4)
echo "From worker: $result\n";//这里主进程,接受到的子进程的数据
}
for($i = 0; $i < $worker_num; $i++)
{
$ret = swoole_process::wait();//回收结束运行的子进程(5)
$pid = $ret['pid'];
unset($workers[$pid]);
echo "Worker Exit, PID=".$pid.PHP_EOL;
}
运行结果:
例子1:
例子2: