我读到了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));此代码是否全部运行,或等待1执行另一个?
发布于 2020-01-12 03:16:18
这是使用stream_select功能。它不是像你想的那样并行运行的。它的工作方式是在流可读/可写时注册要调用的回调,然后在等待的特定承诺完成后返回。同时解决的所有其他承诺都已完成并缓存在各自的承诺中,等待您使用yield或Promise::onResolve展开值。安培事件循环是管理多个套接字并为您处理并发性的工具。
如果您想要一个基本的示例,说明这是如何工作的,我在GitHub上放置了一个示例项目,它是两个类,但基于Curl而不是stream_select:https://github.com/kwhat/requestful
前7种方法是设置允诺接口所需的全部内容。这里所有的神奇之处都是基于传递给构造函数的两个回调以及当时/取消回调周围的包装器。
sendRequestAsync方法是如何创建并发Curl请求的。所有的魔术都发生在对任何承诺的回调等待()中,它调用一个实习生在循环中调用tick方法的匿名函数。tick()方法是解决所有承诺的方法,而不管您调用哪个承诺。
https://stackoverflow.com/questions/59700282
复制相似问题