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