Swoole Coroutine WaitGroup

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

  • Swoole\Coroutine\WaitGroup->__construct
  • Swoole\Coroutine\WaitGroup->add
  • Swoole\Coroutine\WaitGroup->done
  • Swoole\Coroutine\WaitGroup->wait
  • Swoole\Coroutine\batch

    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(0.3);
            $results[] = 'a';
            $wg->done();
        });
    
        go(function () use ($wg, &$results) {
            $wg->add();
            co::sleep(0.7);
            $results[] = 'b';
            $wg->done();
        });
    
        $wg->wait(1);
        var_dump($results);
    });