Vapm
  • About
    • Why is it called unblocking?
    • Next update?
    • Credit
    • Info
  • System
    • runEventLoop()
    • runSingleEventLoop()
    • setTimeout()
    • setInterval()
    • fetch()
    • read()
    • time() & timeEnd()
  • Asynchronous
    • getId()
    • await()
  • Promise
    • c()
    • getId()
    • getFiber()
    • isJustGetResult()
    • getTimeOut()
    • getTimeStart()
    • getTimeEnd()
    • setTimeEnd()
    • canDrop()
    • getStatus()
    • getResult()
    • getReturn()
    • getCallback()
    • resolve() & reject()
    • then() & catch() & finally()
    • useCallbacks()
    • all()
    • allSettled()
    • any()
    • race()
    • Some common methods
  • CoroutineGen
    • runBlocking()
    • runNonBlocking()
    • Deferred
    • Deferred Await All
    • repeat() & delay()
    • Channel
      • Example about Channel
    • AwaitGroup
      • Example
    • Mutex
      • Example
    • Goroutine vs CoroutineGen
      • Concurrency
  • Thread
    • How do I create a thread?
    • How do I share data between threads?
    • Advanced Thread
  • Worker
    • Example
  • Stream
    • read()
    • write()
    • append()
    • delete()
    • create()
    • overWrite()
  • FAQ
    • Why System::runEventLoop() and System::runSingleEventLoop() ?
    • Do you want concurrency?
  • PocketMine-PMMP
Powered by GitBook
On this page
  1. CoroutineGen
  2. Channel

Example about Channel

Example:

<?php

declare(ticks=1);

use vennv\vapm\CoroutineGen;
use vennv\vapm\Channel;

$channel = new Channel();

CoroutineGen::runNonBlocking(function() use (&$channel) {
    yield from $channel->receiveGen(function ($result) use (&$channel) {
        echo "A: $result\n";
    });
});

CoroutineGen::runNonBlocking(function() use (&$channel) {
    yield from $channel->receiveGen(function ($result) {
        echo "B: $result\n";
    });
});

CoroutineGen::runNonBlocking(function() use (&$channel) {
    for ($i = 0; $i < 10; $i++) {
        yield from $channel->sendGen($i);
    }
    $channel->close(); // You need must close the channel after sending all the messages
});

Output:

A: 0
B: 1
A: 2
B: 3
A: 4
B: 5
A: 6
B: 7
A: 8
B: 9

Another example:

<?php

declare(ticks=1);

use vennv\vapm\Channel;
use vennv\vapm\CoroutineGen;

$channel = new Channel();
CoroutineGen::runNonBlocking(
    function () use (&$channel) {
        for ($i = 0; $i < 10; $i++) {
            yield from $channel->sendGen($i);
        }
        $channel->close();
    },
);

$channel->receive(function ($result) {
    echo "Channel: $result\n";
});

Output:

Channel: 0
Channel: 1
Channel: 2
Channel: 3
Channel: 4
Channel: 5
Channel: 6
Channel: 7
Channel: 8
Channel: 9
PreviousChannelNextAwaitGroup

Last updated 8 months ago