并发循环中的 Amp Promises 使用指南

霞舞
发布: 2025-09-04 18:43:15
原创
611人浏览过

并发循环中的 amp promises 使用指南

本文将解决在使用 Amp 框架进行并发编程时,特别是在循环中使用 Promises 时遇到的问题。通过一个实际的下载场景示例,展示了如何正确地使用 Amp\Promise\all() 来并发执行多个 Promise,并提供了一种解决 Promise 在循环中不返回或抛出异常的方案,帮助开发者更好地理解和应用 Amp 的异步编程模型。

在使用 Amp 框架进行异步编程时,经常会遇到需要在循环中并发执行多个任务的场景。例如,从多个 URL 下载数据,或者处理大量数据块。然而,直接在循环中使用 Amp\Promise\all() 可能会遇到一些问题,例如 Promise 不返回结果或者没有抛出异常,导致程序hang住。

下面的示例代码模拟了一个下载场景,将一个大文件分割成多个 chunk,然后并发下载这些 chunk:

<?php

use Amp\Deferred;
use Amp\Loop;
use Amp\Promise;

class Downloader {

    private $chunkCount = 10;
    private $chunkSize = 1024;
    private $connections = 3;
    private $size = 10240;
    private $path = '/tmp';

    public function __construct(private $app) {}

    /**
     * Start Download
     *
     * @return void
     */
    private function download() {
        $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) {
            $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 Deferred();

                    Loop::delay(3 * 1000, function () use ($url, $deferred) {
                        $deferred->resolve($url);
                    });

                    return $deferred->promise();
                });
            }

            $responses = yield Promise\all($promises);

            foreach ($responses as $url => $response) {
                \printf("Read %d bytes from %s\n", \strlen($response), $url);
            }
        }
    }

    public function runDownload() {
        Loop::run(function () {
            yield $this->download();
        });
    }
}

// 使用示例
Loop::run(function () {
    $downloader = new Downloader(null);
    yield \Amp\call(function() use ($downloader) {
        $downloader->download();
    });
});
登录后复制

在这个例子中,我们首先将要下载的内容分割成多个 chunk,然后将这些 chunk 分组,每组包含一定数量的 chunk,数量由 $this-youjiankuohaophpcnconnections 决定。然后,我们遍历这些分组,为每个分组创建一组 Promise,并使用 Amp\Promise\all() 来并发执行这些 Promise。

问题分析与解决方案

SpeakingPass-打造你的专属雅思口语语料
SpeakingPass-打造你的专属雅思口语语料

使用chatGPT帮你快速备考雅思口语,提升分数

SpeakingPass-打造你的专属雅思口语语料 25
查看详情 SpeakingPass-打造你的专属雅思口语语料

最初的代码中,yield Amp\Promise\all($promises) 并没有返回任何结果,也没有抛出任何异常。这可能是因为 Promise 的执行上下文出现问题。

解决方案是将整个 foreach 循环块包裹在一个 Amp\call() 中,这样可以确保循环中的代码在正确的 Amp 协程上下文中执行。修改后的代码如下:

<?php

use Amp\Deferred;
use Amp\Loop;
use Amp\Promise;

class Downloader {

    private $chunkCount = 10;
    private $chunkSize = 1024;
    private $connections = 3;
    private $size = 10240;
    private $path = '/tmp';

    public function __construct(private $app) {}

    /**
     * Start Download
     *
     * @return void
     */
    private function download() {
        $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);

        yield \Amp\call(function() use ($chunkedChunks) {
            foreach ($chunkedChunks as $key => $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 Deferred();

                        Loop::delay(3 * 1000, function () use ($url, $deferred) {
                            $deferred->resolve($url);
                        });

                        return $deferred->promise();
                    });
                }

                $responses = yield Promise\all($promises);

                foreach ($responses as $url => $response) {
                    \printf("Read %d bytes from %s\n", \strlen($response), $url);
                }
            }
        });
    }

    public function runDownload() {
        Loop::run(function () {
            yield $this->download();
        });
    }
}

// 使用示例
Loop::run(function () {
    $downloader = new Downloader(null);
    yield \Amp\call(function() use ($downloader) {
        $downloader->download();
    });
});
登录后复制

注意事项与总结

  • 协程上下文: 在使用 Amp 进行并发编程时,务必确保代码在正确的协程上下文中执行。Amp\call() 可以用来创建一个新的协程,并确保代码在其中执行。
  • 错误处理: 在并发执行 Promise 时,需要注意错误处理。可以使用 try-catch 块来捕获 Promise 执行过程中抛出的异常。
  • 性能优化: 并发连接数 $this->connections 需要根据实际情况进行调整,以达到最佳的下载速度。过多的并发连接可能会导致服务器压力过大,而过少的并发连接可能会导致下载速度过慢。

通过本文的介绍,相信你已经掌握了在循环中使用 Amp Promises 的基本方法,并能够解决 Promise 不返回或抛出异常的问题。在实际开发中,可以根据具体场景进行调整和优化,以达到最佳的并发性能。

以上就是并发循环中的 Amp Promises 使用指南的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号