Channel::__construct

(PHP 8.6+, True Async 1.0)

public Channel::__construct(int $capacity = 0)

Creates a new channel for passing data between coroutines.

A channel is a synchronization primitive that allows coroutines to safely exchange data. The channel’s behavior depends on the $capacity parameter:

Parameters

capacity
The capacity of the channel’s internal buffer. 0 — rendezvous channel (default), send blocks until receive. Positive number — buffer size.

Examples

Example #1 Rendezvous channel (unbuffered)

<?php

use Async\Channel;

$channel = new Channel(); // capacity = 0

spawn(function() use ($channel) {
    $channel->send('hello'); // suspends until someone calls recv()
    echo "Sent\n";
});

spawn(function() use ($channel) {
    $value = $channel->recv(); // receives 'hello', unblocks the sender
    echo "Received: $value\n";
});

Example #2 Buffered channel

<?php

use Async\Channel;

$channel = new Channel(3); // buffer for 3 elements

spawn(function() use ($channel) {
    $channel->send(1); // does not block — buffer is empty
    $channel->send(2); // does not block — space available
    $channel->send(3); // does not block — last slot
    $channel->send(4); // suspends — buffer is full
});

See also