Swoole Coroutine WaitGroup

4.x is outdated, please check the latest version 22.x


Latest version: pecl install openswoole-22.1.2

We can use WaitGroup to sync multiple coroutines, wait for multiple coroutines to finish.

Launch several coroutines and use add to increment the WaitGroup counter for each. Then use wait to block until the WaitGroup counter goes back to 0.

You can also use the helper function batch to batch executing multiple tasks concurrently and wait all tasks to be finished.

Methods

Example

<?php
declare(strict_types=1);

use Swoole\Coroutine\WaitGroup;

Co\run(function() {
    $wg = new WaitGroup();

    $results = [];
    go(function () use ($wg, &$results) {
        $wg->add();
        co::sleep(3);
        $results[] = 'a';
        $wg->done();
    });

    go(function () use ($wg, &$results) {
        $wg->add();
        co::sleep(7);
        $results[] = 'b';
        $wg->done();
    });

    $wg->wait(10);
    var_dump($results);
});
Last updated on August 31, 2022