Using channel to realize communication (message queue) between corollaries in spool

Time:2021-6-23

passageway

Coroutine\ChannelUsing local memory, memory is isolated between different processes.

It can only be carried out in different processes of the same processpushandpopOperation.

Co::set(['hook_flags'=> SWOOLE_HOOK_ALL]);
Co\run(function(){
    //Set a channel with a capacity of 1
    $chan = new Swoole\Coroutine\Channel(1);
    
    Swoole\Coroutine::create(function () use ($chan) {
        for($i = 0; $i < 100000; $i++) {
            co::sleep(1.0);
            //Write data to the channel and queue when the channel is full
            $chan->push(['rand' => rand(1000, 9999), 'index' => $i]);
            echo "$i pushed! \n";
        }
    });
    
    Swoole\Coroutine::create(function () use ($chan) {
        while(1) {
            $data = $chan->pop();
            var_dump($data);
        }
    });
});