Skip to content

Commit

Permalink
feat Utils/Pool
Browse files Browse the repository at this point in the history
  • Loading branch information
chaz6chez committed Nov 8, 2024
1 parent bdac16f commit 2caf9a8
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions src/Utils/Pool/Pool.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use function Workbunny\WebmanCoroutine\wait_for;

use Workerman\Worker;
use function Workbunny\WebmanCoroutine\wakeup;

class Pool
{
Expand Down Expand Up @@ -203,11 +204,13 @@ public static function idle(string $name): Pool|null
public static function getIdle(string $name, int $timeout = -1): Pool
{
$pool = null;
// 使用pool.idle.$name事件等待空闲对象
wait_for(function () use (&$pool, $name) {
$pool = self::idle($name);

return $pool !== null;
}, $timeout);
}, timeout: $timeout, event: "pool.idle.$name");
// 获取到的对象加锁
$pool->setIdle(false);

return $pool;
Expand Down Expand Up @@ -366,6 +369,14 @@ public function isIdle(): bool
public function setIdle(bool $idle): void
{
$this->_idle = $idle;
if ($idle) {
$id = spl_object_hash($this);
$name = $this->getName();
// 唤醒pool.wait.$name.$id
wakeup("pool.wait.$name.$id");
// 唤醒pool.idle.$name
wakeup("pool.idle.$name");
}
}

/**
Expand Down Expand Up @@ -397,9 +408,12 @@ public function setForce(bool $force): void
*/
public function wait(?\Closure $closure = null): void
{
$id = spl_object_hash($this);
$name = $this->getName();
// 永久等待pool.wait.$name.$id唤醒事件
wait_for(function () {
return $this->isIdle();
});
}, timeout: -1, event: "pool.wait.$name.$id");
if ($closure) {
$this->setIdle(false);
try {
Expand Down

0 comments on commit 2caf9a8

Please sign in to comment.