PHP code example of hyperf / single-flight-incubator
1. Go to this page and download the library: Download hyperf/single-flight-incubator library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
hyperf / single-flight-incubator example snippets
$ret = [];
$barrierKey = uniqid();
run(static function () use (&$ret, $barrierKey) {
for ($i = 0; $i < 10; ++$i) {
go(static function () use (&$ret, $barrierKey, $i) {
$ret[] = SingleFlight::do($barrierKey, static function () use ($i) {
// ensure that other coroutines can be scheduled at the same time
usleep(1000);
return [Coroutine::getCid() => $i];
});
});
}
});
if (count(array_unique($ret)) === 1) {
$ret = var_export($ret, true);
printf("%s\n只有一个协程会执行闭包逻辑,其他协程等待其结果进行复用\n", $ret);
}
run(static function () {
$parties = 10;
$barrier = new CounterBarrier($parties);
$sleepMs = 5;
for ($i = 0; $i < $parties - 1; ++$i) {
go(static function () use ($barrier) {
$waitAt = microtime(true);
$barrier->await();
// your biz logic here
$resumeAt = microtime(true);
$elapsed = ($resumeAt - $waitAt) * 1000;
printf("协程 [%d] 等待 %.2f 毫秒后,恢复执行\n", Coroutine::getCid(), $elapsed);
});
}
go(static function () use ($barrier, $sleepMs) {
usleep($sleepMs * 1000);
printf("协程 [%d] 作为最后一个协程,等待 %d 毫秒后加入屏障,同其他协程一起执行\n", Coroutine::getCid(), $sleepMs);
$barrier->await();
// your biz logic here
});
});