코루틴 대기 그룹 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 서버
$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 타임아웃:false 성공:true
*/
public function wait(int|float $timeout = -1): bool;
}