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 서버
$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;
}