Channel::close
(PHP 8.6+, True Async 1.0)
public Channel::close(): void
Closes the channel. After closing:
- Calling
send()throws aChannelException. - Calling
recv()continues to return values from the buffer until it is empty. After that,recv()throws aChannelException. - All coroutines waiting in
send()orrecv()receive aChannelException. - Iteration via
foreachterminates when the buffer is empty.
Calling close() again on an already closed channel does not cause errors.
Examples
Example #1 Closing a channel after sending data
<?php
use Async\Channel;
$channel = new Channel(10);
spawn(function() use ($channel) {
for ($i = 0; $i < 5; $i++) {
$channel->send($i);
}
$channel->close(); // signal to the receiver that no more data will come
});
spawn(function() use ($channel) {
foreach ($channel as $value) {
echo "Received: $value\n";
}
// foreach terminates after closing and draining the buffer
echo "Channel exhausted\n";
});
Example #2 Handling closure by waiting coroutines
<?php
use Async\Channel;
$channel = new Channel();
spawn(function() use ($channel) {
try {
$channel->send('data'); // waiting for a receiver
} catch (\Async\ChannelException $e) {
echo "Channel closed: {$e->getMessage()}\n";
}
});
spawn(function() use ($channel) {
delay(100); // short delay
$channel->close(); // unblocks the sender with an exception
});
See also
- Channel::isClosed — Check if the channel is closed
- Channel::recv — Receive a value (drains the buffer)
- Channel::getIterator — Iterate until closed