Method
phasync::channel
Creates a channel and returns its two ends in $read and $write.
Description#
public static phasync::channel(
?ReadChannelInterface &$read,
?WriteChannelInterface &$write,
int $bufferSize = 0
): voidA channel passes values from coroutines that write to coroutines that read, in the order written, each value to exactly one reader. Any PHP value can be sent: nothing is serialized. With a $bufferSize of 0, write() returns when a reader has taken the value. With a buffer, write() returns at once while the buffer has room, and waits when it is full. read() waits while the channel is empty.
When the writer closes the channel, readers read what is left, and then see the end: foreach over the reader stops, and read() sets its $eof argument. Writing to a closed channel throws a ChannelException. Dropping the last reference to an end closes the other: that is how a coroutine that serves a channel stops when its peer is gone.
The coroutine that calls channel() is not expected to wait on it itself: if it does, and no other coroutine has waited on the channel within about 100 ms, the wait throws a ChannelException (a likely deadlock). Call activate() on an end to switch that off.
Parameters#
- $read ?ReadChannelInterface
- Receives the reading end
- $write ?WriteChannelInterface
- Receives the writing end
- $bufferSize int = 0
- Values the channel holds before
write()waits; 0: none
Examples#
phasync::run(function () {
phasync::channel($reader, $writer, 10); // a buffer of 10 values
phasync::go(function () use ($writer) {
foreach (['a.txt', 'b.txt', 'c.txt'] as $file) {
$writer->write($file);
}
$writer->close();
});
foreach ($reader as $file) { // ends when the writer closes
echo "processing $file\n";
}
});See also#
phasync::publisherTo deliver every value to many readersReadChannelInterfaceThe reading end of a channel: values written to the channel arrive here in the order they were written.WriteChannelInterfaceThe writing end of a channel:write()sends a value to the readers of the channel.