You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.6 KiB
PHP

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?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();