gpt4 book ai didi

php - Amphp 并行是如何工作的?

转载 作者:行者123 更新时间:2023-12-04 04:19:39 24 4
gpt4 key购买 nike

我在看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 功能。它不是以您所想的常规方式并行运行。它通过注册一个回调来工作,一旦流可读/可写,然后在您等待的特定 promise 完成时返回。同时解决的所有其他 promise 已完成并缓存在各自的 promise 中,等待您使用 yieldPromise::onResolve 解包值。 Amp's event loop是什么在为您管理多个套接字并处理并发。

如果您想了解其工作原理的基本示例,我在 GitHub 上放了一个示例项目,它是两个类,但基于 Curl 而不是 stream_select:https://github.com/kwhat/requestful

first 7 methods是设置 promise 界面所需的全部。这里的所有魔法都基于传递给构造函数的两个回调以及围绕 then/cancel 回调的包装器。

sendRequestAsync method 是如何创建并发 Curl 请求的。神奇的一切都发生在任何 promise 的 wait() 回调中,它调用 anonymous function。该实习生在循环中调用 tick 方法。 tick() 方法是解决所有 promise 的方法,无论您调用哪个 wait on。

关于php - Amphp 并行是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59700282/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com