【问题标题】:How the Amphp parallel works?Amphp 并行是如何工作的?
【发布时间】:2020-04-29 04:50:46
【问题描述】:

我正在阅读有关 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 执行另一个?

【问题讨论】:

    标签: php amphp


    【解决方案1】:

    Amp codebase 可以看出,它会在同一个事件循环中运行您的所有请求。

    鉴于您的请求正在被产生 (yield $client-&gt;request($url)),并且它们是在同一个事件循环中产生的,它们被同时分派。

    我建议您阅读this article through,特别是“异步开发:Amp 框架的工作原理”部分。我认为这将使引擎在幕后的工作方式更加清晰。

    希望这对您有所帮助。干杯! :)

    【讨论】:

    • Artax 不是基于 Curl,所以我编辑了你的答案来纠正这个问题。 :-)
    【解决方案2】:

    这是使用stream_select 功能。它没有以您所想的传统方式并行运行。它的工作原理是注册一个回调,以便在流可读/可写后调用,然后在您等待的特定承诺完成时返回。同时解决的所有其他承诺都已完成并缓存在各自的承诺中,等待您使用yieldPromise::onResolve 解包值。 Amp's event loop 负责管理多个套接字并为您处理并发。

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

    first 7 methods 是设置 Promise 接口所需的全部内容。这里所有的魔法都基于传递给构造函数的两个回调以及 then/cancel 回调的包装器。

    sendRequestAsync 方法是创建并发 Curl 请求的方式。魔术都发生在任何 promise 上的 wait() 回调中,它调用 anonymous function,实习生在循环中调用 tick 方法。 tick() 方法解决了所有的承诺,不管你叫哪个等待。

    【讨论】:

    • 不,它没有使用curl_multi,它根本没有使用Curl。在没有扩展的情况下,它使用stream_select() 和非阻塞I/O,并基于PHP 的stream_* 函数实现HTTP 协议和流。
    猜你喜欢
    • 2017-06-22
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 2011-06-27
    • 2017-06-06
    • 2015-12-07
    • 2011-09-13
    • 2019-04-21
    相关资源
    最近更新 更多