58 lines
1.6 KiB
PHP
58 lines
1.6 KiB
PHP
<?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(); |