From 553029ea6f921ae537d33023929913af0176684a Mon Sep 17 00:00:00 2001 From: VennV <111500380+VennDev@users.noreply.github.com> Date: Sun, 1 Sep 2024 01:17:26 +0700 Subject: [PATCH] Update Channel.php --- src/vennv/vapm/Channel.php | 46 +++++++++++++++++++++++++------------- 1 file changed, 30 insertions(+), 16 deletions(-) diff --git a/src/vennv/vapm/Channel.php b/src/vennv/vapm/Channel.php index 378296ed6..7d596bd18 100644 --- a/src/vennv/vapm/Channel.php +++ b/src/vennv/vapm/Channel.php @@ -36,21 +36,31 @@ interface ChannelInterface * * This function is used to send a message to the channel. */ - public function send($message): Generator; + public function sendGen($message): Generator; /** + * @param mixed $message + * @return void + * + * This function is used to send a message to the channel. + */ + public function send($message): void; + + /** + * @param callable $callback * @return Generator * * This function is used to receive a message from the channel. */ - public function receiveGen(): Generator; + public function receiveGen(callable $callback): Generator; /** - * @return mixed + * @param callable $callback + * @return void * * This function is used to receive a message from the channel. */ - public function receive(): mixed; + public function receive(callable $callback): void; /** * @return bool @@ -87,7 +97,7 @@ final class Channel implements ChannelInterface private bool $closed = false; - public function send($message): Generator + public function sendGen($message): Generator { $this->exceptionIfClosed(); while ($this->locked) yield; @@ -96,29 +106,33 @@ public function send($message): Generator $this->locked = false; } - public function receiveGen(): Generator + public function send($message): void { $this->exceptionIfClosed(); while ($this->locked) { CoroutineGen::run(); - yield; } $this->locked = true; - $message = array_shift($this->queue); + $this->queue[] = $message; $this->locked = false; - return yield $message; } - public function receive(): mixed + public function receiveGen(callable $callback): Generator { - $this->exceptionIfClosed(); - while ($this->locked) { + while (!$this->closed || !empty($this->queue)) { + $message = array_shift($this->queue); + if ($message !== null) $callback($message); + yield; + } + } + + public function receive(callable $callback): void + { + while (!$this->closed || !empty($this->queue)) { + $message = array_shift($this->queue); + if ($message !== null) $callback($message); CoroutineGen::run(); } - $this->locked = true; - $message = array_shift($this->queue); - $this->locked = false; - return $message; } public function isEmpty(): bool