OpenSwoole Coroutine WaitGroup

Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5

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.

You have to install OpenSwoole core library with composer require openswoole/core to use this feature.

Methods

Example

<?php
declare(strict_types=1);

use OpenSwoole\Core\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 February 9, 2023