Parallel

Parallel 是一個並行任務調度工具,允許在程式中同時執行多個非同步任務,並在所有任務完成後獲取結果。Parallel 是基於 Barrier 實現的。

注意
底層自動識別驅動類型,僅支持 Swoole/Swow/Fiber 驅動

提示
此特性需要 workerman>=5.1.0

<?php
use Workerman\Connection\TcpConnection;
use Workerman\Coroutine\Parallel;
use Workerman\Events\Swoole;
use Workerman\Protocols\Http\Request;
use Workerman\Worker;
require_once __DIR__ . '/vendor/autoload.php';

// Http Server
$worker = new Worker('http://0.0.0.0:8001');
$worker->eventLoop = Swoole::class; // 或 Swow::class 或 Fiber::class
$worker->onMessage = function (TcpConnection $connection, Request $request) {
    $parallel = new Parallel();
    for ($i=1; $i<5; $i++) {
        $parallel->add(function () use ($i) {
            // 執行某些操作
            return $i;
        });
    }
    $results = $parallel->wait();
    $connection->send(json_encode($results)); // 回應: [1,2,3,4]
};
Worker::runAll();

接口說明

interface ParallelInterface
{
    /**
     * 構造函數,$concurrent 為並行任務數,-1 表示不限制並行任務數
     */
    public function __construct(int $concurrent = -1);

    /**
     * 添加一個並行任務
     */
    public function add(callable $callable, ?string $key = null): void;

    /**
     * 等待所有任務完成並返回結果
     */
    public function wait(): array;

    /**
     * 獲取任務中發生異常的結果
     */
    public function getExceptions(): array;
}