Swoole Channel

Memory data structure likes Chan in Golang, implemented based on shared memory and Mutex locks. It can be used as high performance message queue in memory.

Swoole\Channel::\_\_construct(int $size)

Alias: swoole_channel->__construct(int $size)

Construct a swoole channel with fixed size.

Swoole\Channel::push(mixed $data)

Alias: swoole_channel->push(mixed $data)

Write and push data into swoole channel.

Swoole\Channel::pop()

Alias: swoole_channel->pop()

Read and pop data from swoole channel.

Swoole\Channel::stats()

Alias: swoole_channel->stats()

Get stats of swoole channel: the numbers of queued elements and total size of the memory used by the queue:

<?php
array(
  "queue_num" => 10,
  "queue_bytes" => 161,
);

Example

<?php
$chan = new Swoole\Channel(1024 * 256);
$n = 100000;
$bytes = 0;
if (pcntl_fork() > 0)
{
    echo "Parent process\n";
    for ($i = 0; $i < $n; $i++)
    {
        $data = str_repeat('A', rand(100, 200));
        if ($chan->push($data) === false)
        {
            echo "The channel is full\n";
            usleep(1000);
            $i--;
            continue;
        }
        $bytes += strlen($data);
    }
    echo "Total pushed data size: $bytes bytes\n";
    var_dump($chan->stats());
}
else
{
    echo "Child process\n";
    for ($i = 0; $i < $n; $i++)
    {
        $data = $chan->pop();
        if ($data === false)
        {
            echo "The channel is empty\n";
            usleep(1000);
            $i--;
            continue;
        }
        $bytes += strlen($data);
    }
    echo "Total popped data size: $bytes bytes\n";
    var_dump($chan->stats());
}