OpenSwoole\Coroutine\Channel->push()

Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5

Declaration

<?php OpenSwoole\Coroutine\Channel->push(mixed $data, float $timeout = -1): bool

Parameters

data

The data you want to add to the channel stack, can be any PHP variable, including anonymous functions and resources.

timeout

Sets the timeout period for when the channel is full, false will be returned if the timeout is reached

Return

A successful push will return true and a closed channel or timeout will return false.

OpenSwoole Coroutine Channel Push

Description

Writes data to the channel.

Quick Usage Example

Wait and push one element into the queue of the channel.

<?php

$chan = new OpenSwoole\Coroutine\Channel(1);

co::run(function () use ($chan) {
    $cid = OpenSwoole\Coroutine::getCid();
    $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 = OpenSwoole\Coroutine::getCid();
    while(1) {
        $data = $chan->pop();
        echo "[coroutine $cid]\n";
        var_dump($data);
    }
});

Notes

Coroutine channels use local memory, memory is isolated between different processes. Only in same process push and pop operations work with different coroutines.

You can use $channel->errCode to access the error code for more detail on what happened.

To avoid ambiguity, do not write data into an empty channel that could be classed as an error, such as 0, false, an empty string or null.

Last updated on September 4, 2022