Swoole4提供的PHP协程语法借鉴自Golang,在此向GO开发组致敬
PHP+Swoole协程可以与Golang很好地互补。Golang:静态语言,严谨强大性能好,PHP+Swoole:动态语言,灵活简单易用
如果有2个协程并发执行,另外一个协程,需要依赖这两个协程的执行结果,如果解决此问题呢?
答案就是使用通道(Channel)它有两个接口push和pop:
push:向通道中写入内容,如果已满,它会进入等待状态,有空间时自动恢复
pop:从通道中读取内容,如果为空,它会进入等待状态,有数据时自动恢复
案例:
$chan = new chan(2);
# 协程1
go (function () use ($chan) {
$result = [];
for ($i = 0; $i < 2; $i++)
{
$result += $chan->pop();
}
var_dump($result);
});
# 协程2
go(function () use ($chan) {
$cli = new Swoole\Coroutine\Http\Client(‘www.qq.com’, 80);
$cli->set([‘timeout’ => 10]);
$cli->setHeaders([
‘Host’ => “www.qq.com”,
“User-Agent” => ‘Chrome/49.0.2587.3’,
‘Accept’ => ‘text/html,application/xhtml+xml,application/xml’,
‘Accept-Encoding’ => ‘gzip’,
]);
$ret = $cli->get(‘/’);
// $cli->body 响应内容过大,这里用 Http 状态码作为测试
$chan->push([‘www.qq.com’ => $cli->statusCode]);
});
# 协程3
go(function () use ($chan) {
$cli = new Swoole\Coroutine\Http\Client(‘www.163.com’, 80);
$cli->set([‘timeout’ => 10]);
$cli->setHeaders([
‘Host’ => “www.163.com”,
“User-Agent” => ‘Chrome/49.0.2587.3’,
‘Accept’ => ‘text/html,application/xhtml+xml,application/xml’,
‘Accept-Encoding’ => ‘gzip’,
]);
$ret = $cli->get(‘/’);
// $cli->body 响应内容过大,这里用 Http 状态码作为测试
$chan->push([‘www.163.com’ => $cli->statusCode]);
});
创建了3个协程
协程1循环两次对通道进行pop,因为队列为空,它会进入等待状态
协程2和协程3执行完成后,会push数据,协程1拿到了结果,继续向下执行
延迟任务
Swoole\Runtime::enableCoroutine();
go(function () {
echo “a”;
defer(function () {
echo “~a”;
});
echo “b”;
defer(function () {
echo “~b”;
});
sleep(1);
echo “c”;
});
执行结果:abc~b~a
相关文章
本站已关闭游客评论,请登录或者注册后再评论吧~