協(xié)程屏障 Barrier
Barrier 是一個(gè)用于協(xié)程同步的工具,允許在異步任務(wù)中等待所有協(xié)程執(zhí)行完成后再繼續(xù)后續(xù)邏輯。Barrier是基于PHP引用計(jì)數(shù)實(shí)現(xiàn)的。
注意
底層自動(dòng)識(shí)別驅(qū)動(dòng)類型,僅支持Swoole/Swow/Fiber驅(qū)動(dòng)提示
此特性需要 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; // Or Swow::class or Fiber::class
$worker->onMessage = function (TcpConnection $connection, Request $request) {
$barrier = Barrier::create();
for ($i=1; $i<5; $i++) {
Coroutine::create(function () use ($barrier, $i) {
// Do something
});
}
// Wait all coroutine done
Barrier::wait($barrier);
$connection->send('All Task Done');
};
Worker::runAll();
接口說明
interface BarrierInterface
{
/**
* 創(chuàng)建一個(gè)新的Barrier實(shí)例
*/
public static function create(): object;
/**
* 暫停當(dāng)前協(xié)程,等待指定Barrier中的所有協(xié)程任務(wù)完成
*/
public static function wait(object &$barrier, int $timeout = -1): void;
}