Coroutine WaitGroup

WaitGroup is similar to Barrier, it is a tool for coroutine synchronization that allows waiting for all coroutines to complete execution before continuing with subsequent logic in asynchronous tasks.

The difference from Barrier is that WaitGroup allows developers to control the increment and decrement of the count.

Note
The underlying system automatically recognizes 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) {
    $wg = new WaitGroup();
    for ($i=1; $i<5; $i++) {
        $wg->add();
        Coroutine::create(function () use ($wg, $i) {
            try {
            // Do something
            } finally {
                $wg->done();
            }
        });
    }
    // Wait all coroutine done, timeout after 10 seconds
    $result = $wg->wait(10.0);
    if (!$result) {
        $connection->send('WaitGroup Timeout');
        return;
    }
    $connection->send('All Task Done');
};

Worker::runAll();

Interface Description

interface WaitGroupInterface
{

    /**
     * Increment the count
     *
     * @param int $delta
     * @return bool
     */
    public function add(int $delta = 1): bool;

    /**
     * Mark completion
     *
     * @return bool
     */
    public function done(): bool;

    /**
     * Return the count
     *
     * @return int
     */
    public function count(): int;

    /**
     * Coroutine wait
     *
     * @param int|float $timeout second
     * @return bool timeout:false success:true
     */
    public function wait(int|float $timeout = -1): bool;
}