|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace ReactParallel\Tests\Tests; |
| 6 | + |
| 7 | +use ReactParallel\Contracts\ClosedException; |
| 8 | +use ReactParallel\Contracts\PoolInterface; |
| 9 | +use ReactParallel\EventLoop\EventLoopBridge; |
| 10 | +use ReactParallel\Runtime\Runtime; |
| 11 | +use WyriHaximus\PoolInfo\Info; |
| 12 | + |
| 13 | +final class ImmidiatePool implements PoolInterface |
| 14 | +{ |
| 15 | + private int $activeThreads = 0; |
| 16 | + private bool $closed = false; |
| 17 | + /** @var array<Runtime> */ |
| 18 | + private array $runtimes = []; |
| 19 | + |
| 20 | + public function __construct(private readonly EventLoopBridge $eventLoopBridge) |
| 21 | + { |
| 22 | + } |
| 23 | + |
| 24 | + /** |
| 25 | + * {@inheritDoc} |
| 26 | + */ |
| 27 | + public function info(): iterable |
| 28 | + { |
| 29 | + yield Info::TOTAL => $this->activeThreads; |
| 30 | + yield Info::BUSY => $this->activeThreads; |
| 31 | + yield Info::CALLS => 0; |
| 32 | + yield Info::IDLE => 0; |
| 33 | + yield Info::SIZE => $this->activeThreads; |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * {@inheritDoc} |
| 38 | + */ |
| 39 | + public function run(\Closure $callable, array $args = []): mixed |
| 40 | + { |
| 41 | + if ($this->closed === true) { |
| 42 | + throw ClosedException::create(); |
| 43 | + } |
| 44 | + |
| 45 | + $runtime = Runtime::create($this->eventLoopBridge); |
| 46 | + $this->runtimes[\spl_object_id($runtime)] = $runtime; |
| 47 | + $this->activeThreads++; |
| 48 | + try { |
| 49 | + $result = $runtime->run($callable, $args); |
| 50 | + } finally { |
| 51 | + unset($this->runtimes[\spl_object_id($runtime)]); |
| 52 | + } |
| 53 | + $this->activeThreads--; |
| 54 | + |
| 55 | + return $result; |
| 56 | + } |
| 57 | + |
| 58 | + public function close(): bool |
| 59 | + { |
| 60 | + $this->closed = true; |
| 61 | + |
| 62 | + foreach ($this->runtimes as $runtime) { |
| 63 | + $runtime->close(); |
| 64 | + } |
| 65 | + |
| 66 | + return true; |
| 67 | + } |
| 68 | + |
| 69 | + public function kill(): bool |
| 70 | + { |
| 71 | + $this->closed = true; |
| 72 | + |
| 73 | + foreach ($this->runtimes as $runtime) { |
| 74 | + $runtime->kill(); |
| 75 | + } |
| 76 | + |
| 77 | + return true; |
| 78 | + } |
| 79 | +} |
0 commit comments