swoole_exmple/Server/process.php
Wenbin.Wang 1be654dd5f 代码
2021-12-24 16:44:53 +08:00

58 lines
1.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
class process
{
protected $worker = [];
/**
* 执行进程工作
*/
public function doJob()
{
// 显示主程序开始时间
echo 'process-start-time:' . date('Y-m-d H:i:s') . PHP_EOL;
// 创建10个子进程来执行耗时逻辑
for ($i = 0; $i < 10; $i++) {
// 第二个参数$redirect_stdin_and_stdout为重定向子进程的标准输入和输出设置成true会把输出结果写入到主进程管道
// 第三个参数在第二个参数为false时可设置作用为子进程创建管道如果第二个参数设置成true则这个参数强制为true
$process = new Swoole\Process(function (swoole_process $worker) use ($i) {
$res = $this->job($i);
// 把结果写入管道
$worker->write($res);
}, true);
// 启动进程,返回进程号
$pid = $process->start();
$this->worker[$pid] = $process;
}
// 显示主程序结束时间
echo 'process-end-time:' . date('Y-m-d H:i:s') . PHP_EOL;
}
/**
* 显示进程结果
*/
public function getChannelResponse()
{
foreach ($this->worker as $worker) {
// 通过读取每个管道中的结果来进行显示
echo $worker->read();
}
}
/**
* 进程工作逻辑模拟耗时1s的任务
* @param int $i
* @return string
*/
protected function job(int $i)
{
sleep(1);
return "job {$i} success" . PHP_EOL;
}
}
$pro = new process();
$pro->doJob();
$pro->getChannelResponse();