phasync
phasync / channel

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
): void

A 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#

Example 1
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#