Coroutine Channel

Channel is one of the most important concepts in Swoole PHP Coroutine.

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 or batch 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

    Attributes

    Swoole\Coroutine\Channel->$capacity

    The queue capacity of the channel.

    Swoole\Coroutine\Channel->$errCode

    Get he error code of the channel.

    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();
    });