Channel Coroutine Channel

Channel is a mechanism for communication between coroutines. One coroutine can push data into the channel, while another coroutine can pop data from it, achieving synchronization and data sharing between coroutines.

Tip
This feature requires workerman>=5.1.0

Note

  • Automatically supports Swoole/Swow/Fiber/Select/Event driven at the underlying layer.
  • When using Select/Event driven, the timeout parameters for pop/push are not supported.
<?php
use Workerman\Connection\TcpConnection;
use Workerman\Coroutine\Channel;
use Workerman\Coroutine;
use Workerman\Events\Swoole;
use Workerman\Protocols\Http\Request;
use Workerman\Worker;
require_once __DIR__ . '/vendor/autoload.php';

// Http Server
$worker = new Worker('http://0.0.0.0:8001');
$worker->eventLoop = Swoole::class; // Or Swow::class or Fiber::class
$worker->onMessage = function (TcpConnection $connection, Request $request) {
    $channel = new Channel(2);
    Coroutine::create(function () use ($channel) {
        $channel->push('Task 1 Done');
    });
    Coroutine::create(function () use ($channel) {
        $channel->push('Task 2 Done');
    });
    $result = [];
    for ($i = 0; $i < 2; $i++) {
        $result[] = $channel->pop();
    }
    $connection->send(json_encode($result)); // Response: ["Task 1 Done","Task 2 Done"]
};
Worker::runAll();

Interface Description

interface ChannelInterface
{
    /**
     * Push data into the channel, supporting timeout (in seconds), returns false on timeout.
     */
    public function push(mixed $data, float $timeout = -1): bool;

    /**
     * Pop data from the channel, supporting timeout (timeout in seconds), returns false on timeout.
     */
    public function pop(float $timeout = -1): mixed;

    /**
     * Get the length of data in the channel.
     */
    public function length(): int;

    /**
     * Get the capacity of the channel.
     */
    public function getCapacity(): int;

    /**
     * Whether there are consumers, i.e., whether there are coroutines waiting to pop data.
     */
    public function hasConsumers(): bool;

    /**
     * Whether there are producers, i.e., whether there are coroutines waiting to push data into the channel.
     */
    public function hasProducers(): bool;

    /**
     * Close the channel.
     */
    public function close(): void;

}