swoole初探笔记2 进程处理

当启动一个swoole 会创建2(一个master进程一个manager进程)+n(worker进程)+m个进程(TaskWorker进程)

swoole初探笔记2 进程处理_第1张图片
image.png

1 、创建进程及进程事件


/**
 * create event
 * 进程事件
 */
$workers = []; //process pool 进程 数组

$worker_num = 3; //process num 创建进程的数据量

for($i=0;$i<$worker_num;$i++)
{
    $process = new swoole_process('doProcess'); //创建单独的新进程
    $pid = $process->start(); //start process 启动进程 获取进程id
    $workers[$pid] = $process; //存入 进程数组
}

//process function 创建进程执行函数
function doProcess(swoole_process $process)
{
    $process->write("PID: $process->pid "); //子进程写入信息 ?pipe写入管道
    echo "写入信息: $process->pid $process->callback \n";
}

//add event 添加进程事件
foreach($workers as $process){
    //add
    swoole_event_add($process->pipe,function($pipe) use($process){
        $data = $process->read(); //能否读取数据
        echo "接收到: $data \n";
    });
}
swoole初探笔记2 进程处理_第2张图片
image.png

2、进程队列通信

string swoole_process->pop($maxsize = 8192);
bool swoole_process->push(string $data);

$workers = []; //进程仓库
$worker_num = 2; //最大进程数

for($i=0;$i<$worker_num;$i++){
    $process = new swoole_process('doprocess',false,false); //创建子进程完成
    $process->useQueue(); //开启队列,类似于全局函数
    $pid = $process->start();
    $workers[$pid] = $process;
}

//进程执行函数
function doProcess(swoole_process $process)
{
    $recv = $process->pop();//默认8192个长度
    echo "从主进程获取到数据:$recv \n";
    sleep(5);
    $process->exit(0);
}

//主进程向子进程添加数据
foreach($workers as $pid => $process){
    $process->push("放入子进程 $pid \n");
}

//等待子进程结束 回收资源
for($i=0;$i<$worker_num;$i++){
    $ret = swoole_process::wait(); //等待执行完成
    $pid = $ret['pid'];
    unset($workers['$pid']);
    echo "子进程退出 $pid \n";
}
3、进程信号触发器

swoole_process::signal($signo,$callback) 接收信号
swoole_process::alarm() 发出信号

//触发函数 异步执行
swoole_process::signal(SIGALRM,function (){
    //echo "1\n";
    //达到10次停止
    static $i=0;
    echo "$i \n";
    $i++;
    if($i>10){
        swoole_process::alarm(-1); //清除定时器
    }
});

//定时信号
swoole_process::alarm(100 * 1000);

你可能感兴趣的:(swoole初探笔记2 进程处理)