Swoole Coroutine Channel: Overview, Methods, and Example Usage
This article introduces Swoole's Coroutine Channel for inter‑coroutine communication, explains its memory‑efficient implementation and key methods such as __construct, push, pop, stats, close, length, isEmpty, isFull, capacity and errCode, and provides a complete PHP example demonstrating producer‑consumer behavior.
Swoole\Coroutine\Channel is a high‑performance communication primitive for coroutines, supporting multiple producers and consumers. It operates entirely in memory without additional I/O, leveraging PHP's reference counting for zero‑copy data handling.
Implementation principles
The channel works like PHP's Array class, using only memory and no extra resource allocation.
It relies on PHP reference counting, so even large strings or arrays are passed without copying.
The underlying channel object is reference‑counted, providing zero‑copy semantics.
Key methods
__construct(int $capacity = 1) : creates a channel with the specified buffer capacity (minimum 1).
push(mixed $data, float $timeout = -1): bool : writes data into the channel; optional timeout (seconds, supports float). Returns false on timeout or when the channel is closed.
pop(float $timeout = -1): mixed : reads data from the channel; optional timeout (seconds). Returns false on timeout or when the channel is closed.
stats(): array : returns an array with consumer_num , producer_num and queue_num (for buffered channels also includes queue_size ).
close(): bool : closes the channel and wakes all waiting producers and consumers, causing subsequent push / pop calls to return false .
length(): int : returns the current number of elements in the buffer.
isEmpty(): bool and isFull(): bool : check whether the channel is empty or full.
capacity: int (property): the buffer capacity set at construction (minimum 1).
errCode: int (property): the last error code.
Example usage
<?php
Co\run(function () {
$chan = new Swoole\Coroutine\Channel(1);
// Producer coroutine
Swoole\Coroutine::create(function () use ($chan) {
for ($i = 0; $i < 100000; $i++) {
co::sleep(1.0);
$chan->push(['rand' => rand(1000, 9999), 'index' => $i]);
echo "{$i}\n";
}
});
// Consumer coroutine
Swoole\Coroutine::create(function () use ($chan) {
while (1) {
$data = $chan->pop();
var_dump($data);
}
});
});
?>The example creates a channel with capacity 1, launches a producer coroutine that pushes associative arrays containing a random number and an index, and a consumer coroutine that continuously pops and dumps the received data.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.