[英]How the Amphp parallel works?
我正在阅读有关 amphp 的内容,但我对并行有疑问
示例代码:
<?php
require __DIR__ . '/vendor/autoload.php';
$client = new Amp\Artax\DefaultClient;
$promises = [];
$urls = [
"http://google.com.br",
"http://facebook.com.br",
"http://xat.com/",
"http://kobra.ninja/",
"http://wikipedia.com",
"http://manualdomundo.com.br",
"http://globo.com",
"http://gmail.com"
];
foreach ($urls as $url) {
$promises[$url] = Amp\call(function () use ($client, $url) {
// "yield" inside a coroutine awaits the resolution of the promise
// returned from Client::request(). The generator is then continued.
$response = yield $client->request($url);
// Same for the body here. Yielding an Amp\ByteStream\Message
// buffers the entire message.
$body = yield $response->getBody();
echo $url;
return $url;
});
}
$responses = Amp\Promise\wait(Amp\Promise\all($promises));
这段代码是运行所有 curl 还是等待 1 执行另一个?
这是使用stream_select
功能。 它不是以您所想的传统方式并行运行。 它的工作原理是注册一个回调以在流可读/可写后调用,然后在您等待的特定承诺完成时返回。 在此期间解决的所有其他承诺都已完成并缓存在各自的承诺中,等待您使用yield
或Promise::onResolve
解开该值。 Amp 的事件循环负责管理多个套接字并为您处理并发。
如果你想要一个基本的例子来说明它是如何工作的,我在 GitHub 上放了一个示例项目,它是两个类,但基于 Curl 而不是stream_select
: https : //github.com/kwhat/requestful
前 7 个方法是设置 promise 接口所需的全部方法。 这里的所有魔法都基于传递给构造函数的两个回调以及围绕 then/cancel 回调的包装器。
sendRequestAsync方法是创建并发 Curl 请求的方式。 神奇的一切都发生在任何 promise 的 wait() 回调中,它调用匿名函数,该函数在循环中调用 tick 方法。 这个tick()
方法解决了所有的promise,不管你调用哪个promise。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.