Join 4,000+ others and never miss out on new tips, tutorials, and more.
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.
OpenSwoole\Core\Coroutine\WaitGroup->__construct
OpenSwoole\Core\Coroutine\WaitGroup->add
OpenSwoole\Core\Coroutine\WaitGroup->done
OpenSwoole\Core\Coroutine\WaitGroup->wait
OpenSwoole\Core\Coroutine\WaitGroup->count
OpenSwoole\Core\Coroutine\batch
OpenSwoole\Core\Coroutine\parallel
<?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);
});