Coroutine Barrier

Barrier is a tool for coroutine synchronization that allows waiting for all coroutines to complete before proceeding with subsequent logic in asynchronous tasks. The Barrier is implemented based on PHP's reference counting.

Note
The underlying system automatically detects the driver type and only supports Swoole/Swow/Fiber drivers.

Tip
This feature requires workerman>=5.1.0.

<?php
use Workerman\Connection\TcpConnection;
use Workerman\Coroutine\Barrier;
use Workerman\Coroutine;
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; // Or Swow::class or Fiber::class
$worker->onMessage = function (TcpConnection $connection, Request $request) {
    $barrier = Barrier::create();
    for ($i=1; $i<5; $i++) {
        Coroutine::create(function () use ($barrier, $i) {
            // Do something
        });
    }
    // Wait all coroutine done
    Barrier::wait($barrier);
    $connection->send('All Task Done');
};

Worker::runAll();

Interface Description

interface BarrierInterface
{
    /**
     * Create a new instance of Barrier
     */
    public static function create(): object;

    /**
     * Suspend the current coroutine, waiting for all coroutine tasks in the specified Barrier to complete
     */
    public static function wait(object &$barrier, int $timeout = -1): void;
}