協程等待組 WaitGroup
WaitGroup 與 Barrier 相似,是一個用於協程同步的工具,允許在異步任務中等待所有協程執行完成後再繼續後續邏輯。
與 Barrier 區別的是 WaitGroup 可以由開發者自行控制計數的增加和減少。
注意
底層自動識別驅動類型,僅支持 Swoole/Swow/Fiber 驅動提示
此特性需要 workerman>=5.1.0
<?php
use Workerman\Connection\TcpConnection;
use Workerman\Coroutine\Barrier;
use Workerman\Coroutine;
use Workerman\Events\Swoole;
use Workerman\Protocols\Http\Request;
use Workerman\Worker;
require_once __DIR__ . '/vendor/autoload.php';
// Http Server
$worker = new Worker('http://0.0.0.0:8001');
$worker->eventLoop = Swoole::class; // 或 Swow::class 或 Fiber::class
$worker->onMessage = function (TcpConnection $connection, Request $request) {
$wg = new WaitGroup();
for ($i=1; $i<5; $i++) {
$wg->add();
Coroutine::create(function () use ($wg, $i) {
try {
// 做一些事情
} finally {
$wg->done();
}
});
}
// 等待所有協程完成,超時後為 10 秒
$result = $wg->wait(10.0);
if (!$result) {
$connection->send('WaitGroup 超時');
return;
}
$connection->send('所有任務完成');
};
Worker::runAll();
接口說明
interface WaitGroupInterface
{
/**
* 增加計數
*
* @param int $delta
* @return bool
*/
public function add(int $delta = 1): bool;
/**
* 完成計數
*
* @return bool
*/
public function done(): bool;
/**
* 返回計數
*
* @return int
*/
public function count(): int;
/**
* 協程等待
*
* @param int|float $timeout 秒
* @return bool timeout:false success:true
*/
public function wait(int|float $timeout = -1): bool;
}