
正如摘要所说,本文旨在解决在使用 Amp 进行异步编程时,在循环中处理 Promise 时遇到的阻塞问题。在异步编程中,我们经常需要在循环中发起多个异步操作,并等待它们全部完成。然而,如果直接在循环中使用 yield 等待 Promise,会导致循环阻塞,无法充分利用异步的优势。
下面我们通过一个示例来说明这个问题以及如何解决它。假设我们需要从多个 URL 下载数据,并将下载过程分解为多个 chunk,然后并发地下载这些 chunk。
<?php
use Amp\Loop;
use Amp\Promise;
use Amp\Deferred;
/**
* 模拟下载类
*/
class Downloader
{
private string $path = '/tmp';
private int $chunkCount = 10;
private int $chunkSize = 1024;
private int $connections = 3;
private int $size = 10240; // 总大小
public function __construct(private $app)
{
}
/**
* 开始下载
*
* @return void
*/
public function download(): void
{
$chunks = [];
for ($i = 0; $i < $this->chunkCount + 20; $i++) {
$start = $i * $this->chunkSize;
$end = ($i + 1) * $this->chunkSize;
if ($i == $this->chunkCount - 1) {
$end = $this->size;
}
$chunks[] = (object) ['id' => ($i + 1), 'start' => $start, 'end' => $end, 'path' => $this->path . "/" . $i];
}
$chunkedChunks = array_chunk($chunks, $this->connections);
foreach ($chunkedChunks as $key => $chunkedChunk) {
// 将整个 foreach 块封装在 Amp\call 中
\Amp\Loop::run(function () use ($chunkedChunk) {
$urls = [
'https://secure.php.net',
'https://amphp.org',
'https://github.com',
];
$promises = [];
foreach ($urls as $url) {
$promises[$url] = \Amp\call(function () use ($url) {
$deferred = new \Amp\Deferred();
\Amp\Loop::delay(3 * 1000, function () use ($url, $deferred) {
$deferred->resolve($url);
});
return $deferred->promise();
});
}
$responses = yield \Amp\Promise\all($promises);
foreach ($responses as $url => $response) {
\printf("Read %d bytes from %s\n", \strlen($response), $url);
}
});
}
}
}
// 示例使用
Loop::run(function () {
$downloader = new Downloader(null);
$downloader->download();
});代码解释:
关键点:将 foreach 循环体封装在 Amp\call 中。
如果没有将 foreach 循环体封装在 Amp\call 中,yield Amp\Promise\all($promises) 将会阻塞整个循环,导致每次只能处理一批 Promise,无法实现真正的并发。通过使用 Amp\call,我们创建了一个协程,允许循环中的异步操作并发执行,从而提高了程序的效率。
注意事项:
总结:
在使用 Amp 进行异步编程时,如果需要在循环中处理 Promise,务必将循环体封装在 Amp\call 中,以实现并发执行,避免阻塞主循环。 这样可以充分利用异步编程的优势,提高程序的效率。 理解 Amp\call 的作用是解决循环中 Promise 阻塞问题的关键。
以上就是使用 Amp 并发处理循环中的 Promise的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号