Coroutine Channel

Channel is used for the sync and communction between different coroutines. It is similar to chan in Golang.

The short name chan is the alias of Swoole\Coroutine\Channel.

You can also use WaitGroup to sync coroutines.

Methods

  • Swoole\Coroutine\Channel->__construct
  • Swoole\Coroutine\Channel->push
  • Swoole\Coroutine\Channel->pop
  • Swoole\Coroutine\Channel->close
  • Swoole\Coroutine\Channel->stats
  • Swoole\Coroutine\Channel->length
  • Swoole\Coroutine\Channel->isEmpty
  • Swoole\Coroutine\Channel->isFull
  • Swoole\Coroutine\Channel->capacity
  • Swoole\Coroutine\Channel->errCode

    Example

    <?php
    
    $chan = new Swoole\Coroutine\Channel(1);
    Co\run(function () use ($chan) {
        $cid = Swoole\Coroutine::getuid();
        $i = 0;
        while (1) {
            co::sleep(1.0);
            $chan->push(['rand' => rand(1000, 9999), 'index' => $i]);
            echo "[coroutine $cid] - $i\n";
            $i++;
        }
    });
    Co\run(function () use ($chan) {
        $cid = Swoole\Coroutine::getuid();
        while(1) {
            $data = $chan->pop();
            echo "[coroutine $cid]\n";
            var_dump($data);
        }
    });
    
    <?php
    Co\run(function() {
        $chan = new chan(1);
        $chan->push($data);
        $chan->pop();
    });
    
    Swoole\Coroutine\Channel->__construct(int $capacity = 1)

    Construction method.

    Swoole\Coroutine\Channel->push(mixed $data) : bool

    Write data into channel.

    Swoole\Coroutine\Channel->pop(float $timeout = 0) : mixed

    Read data from channel.

    Swoole\Coroutine\Channel->stats() : array

    Get the stats of the channel.

    Swoole\Coroutine\Channel->close()

    Close channel and resume the other Coroutine.

    Swoole\Coroutine\Channel->length() : int

    Get the number of items in channel.

    Swoole\Coroutine\Channel->isEmpty(): bool

    Check if the channel is empty.

    Swoole\Coroutine\Channel->isFull() : bool

    Check if the channel is full.

    Swoole\Coroutine\Channel->$capacity : int

    The capacity of the channel.

    Swoole\Coroutine\Channel->$errCode : int

    Get he error code of the channel.