首页 > 解决方案 > Amphp 并行是如何工作的?

问题描述

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

标签: phpamphp

解决方案


正如您从Amp 代码库中看到的那样,它将在同一个事件循环中运行您的所有请求。

鉴于您的请求正在被产生(yield $client->request($url)),并且它们在同一个事件循环中被产生,它们被同时调度。

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

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


推荐阅读