mirror of
https://github.com/zhamao-robot/zhamao-framework.git
synced 2026-07-12 03:05:34 +08:00
initial 2.0.0-a2 commit
This commit is contained in:
51
src/ZM/Utils/CoroutinePool.php
Normal file
51
src/ZM/Utils/CoroutinePool.php
Normal file
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace ZM\Utils;
|
||||
|
||||
|
||||
use Swoole\Coroutine;
|
||||
|
||||
class CoroutinePool
|
||||
{
|
||||
private static $cids = [];
|
||||
|
||||
private static $default_size = 30;
|
||||
|
||||
private static $sizes = [];
|
||||
|
||||
private static $yields = [];
|
||||
|
||||
public static function go(callable $func, $name = "default") {
|
||||
if (!isset(self::$cids[$name])) self::$cids[$name] = [];
|
||||
if (count(self::$cids[$name]) >= (self::$sizes[$name] ?? self::$default_size)) {
|
||||
self::$yields[] = Coroutine::getCid();
|
||||
Coroutine::suspend();
|
||||
}
|
||||
go(function () use ($func, $name) {
|
||||
self::$cids[$name][] = Coroutine::getCid();
|
||||
//Console::debug("正在执行协程,当前协程池中有 " . count(self::$cids[$name]) . " 个正在运行的协程: ".implode(", ", self::$cids[$name]));
|
||||
$func();
|
||||
self::checkCids($name);
|
||||
});
|
||||
}
|
||||
|
||||
public static function defaultSize(int $size) {
|
||||
self::$default_size = $size;
|
||||
}
|
||||
|
||||
public static function setSize($name, int $size) {
|
||||
self::$sizes[$name] = $size;
|
||||
}
|
||||
|
||||
private static function checkCids($name) {
|
||||
if (in_array(Coroutine::getCid(), self::$cids[$name])) {
|
||||
$a = array_search(Coroutine::getCid(), self::$cids[$name]);
|
||||
array_splice(self::$cids[$name], $a, 1);
|
||||
$r = array_shift(self::$yields);
|
||||
if ($r !== null) {
|
||||
Coroutine::resume($r);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user