Swoole\Coroutine\Channel::__construct()

4.x is outdated, please check the latest version 22.x


Latest version: pecl install openswoole-22.1.2

Declaration

<?php Swoole\Coroutine\Channel::__construct(int $capacity = 1)

Parameters

capacity

Set the channel max capacity, must be greater than or equal to 1.

Return

A new Swoole Coroutine channel instance.

Swoole Coroutine Channel Constructor

Description

Creates a new channel, allowing you to set the capacity, which cannot be changed once a channel is created.

Quick Usage Example

Wait and pop up one element from the queue of the channel.

<?php

$chan = new Swoole\Coroutine\Channel(1);
Co\run(function () use ($chan) {
    $cid = Swoole\Coroutine::getuid();
    $i = 0;
    while (1) {
        co::sleep(1);
        $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);
    }
});
Last updated on August 31, 2022