Files
kiri-core/kiri-engine/Pool/PoolItem.php
T

116 lines
1.7 KiB
PHP
Raw Normal View History

2023-04-03 13:45:59 +08:00
<?php
2023-04-16 01:45:34 +08:00
declare(strict_types=1);
2023-04-03 13:45:59 +08:00
namespace Kiri\Pool;
2023-04-06 22:15:33 +08:00
use Closure;
2023-04-03 13:45:59 +08:00
use Kiri\Di\Context;
use Swoole\Coroutine\Channel;
class PoolItem
{
/**
2023-04-06 22:15:33 +08:00
* @var Channel|SplQueue
2023-04-03 13:45:59 +08:00
*/
2023-04-06 22:15:33 +08:00
private Channel|SplQueue $_items;
2023-04-03 13:45:59 +08:00
/**
* @var int
*/
private int $created = 0;
/**
* @param int $maxCreated
2023-04-06 22:15:33 +08:00
* @param Closure $callback
2023-04-03 13:45:59 +08:00
*/
2023-04-06 22:15:33 +08:00
public function __construct(readonly public int $maxCreated, readonly public Closure $callback)
2023-04-03 13:45:59 +08:00
{
2023-04-06 22:15:33 +08:00
if (Context::inCoroutine()) {
$this->_items = new Channel($this->maxCreated);
} else {
$this->_items = new SplQueue($this->maxCreated);
}
2023-04-03 13:45:59 +08:00
}
/**
2023-04-06 22:15:33 +08:00
* @param Channel|SplQueue $items
2023-04-03 13:45:59 +08:00
*/
2023-04-06 22:15:33 +08:00
public function setItems(Channel|SplQueue $items): void
2023-04-03 13:45:59 +08:00
{
$this->_items = $items;
}
/**
* @param mixed $item
* @return void
*/
public function push(mixed $item): void
{
$this->_items->push($item);
}
/**
* @return bool
*/
public function isEmpty(): bool
{
return $this->_items->isEmpty();
}
/**
* @return bool
*/
public function size(): bool
{
return $this->_items->length();
}
/**
* @return bool
*/
public function close(): bool
{
return $this->_items->close();
}
/**
* @param int $min
* @return void
*/
public function tailor(int $min = 0): void
{
while ($this->_items->length() > $min) {
$connection = $this->_items->pop(0.000001);
if ($connection instanceof StopHeartbeatCheck) {
$connection->stopHeartbeatCheck();
}
$connection = null;
$this->created -= 1;
}
}
/**
* @param int $waite
* @return mixed
*/
public function pop(int $waite = 10): mixed
{
2023-04-06 23:00:58 +08:00
if ($this->_items->isEmpty()) {
return call_user_func($this->callback);
} else {
2023-04-05 19:58:07 +08:00
return $this->_items->pop();
}
2023-04-03 13:45:59 +08:00
}
}