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. Mutex

Example

<?php

declare(ticks=1);

require_once __DIR__ . '/../../../vendor/autoload.php';

use vennv\vapm\CoroutineGen;
use vennv\vapm\AwaitGroup;
use vennv\vapm\Mutex;

$awaitGroup = new AwaitGroup();
$mutex = new Mutex();
$arr = []; // This is shared between all coroutines

function addText(array &$arr, string $text)
{
    yield $arr[] = $text;
}

$awaitGroup->add(2); // We expect 2 coroutines to run

// This is coroutine A
CoroutineGen::runNonBlocking(function () use (&$arr, &$mutex, &$awaitGroup) {
    yield from $mutex->lock();
    for ($i = 0; $i < 5; $i++) {
        yield from addText($arr, "A");
    }
    yield from $awaitGroup->done();
    yield from $mutex->unlock();
});

// This is coroutine B
CoroutineGen::runNonBlocking(function () use (&$arr, &$mutex, &$awaitGroup) {
    yield from $mutex->lock();
    for ($i = 0; $i < 5; $i++) {
        yield from addText($arr, "B");
    }
    yield from $awaitGroup->done();
    yield from $mutex->unlock();
});

$awaitGroup->wait();

var_dump($arr);

Output:

array(10) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "A"
  [2]=>
  string(1) "A"
  [3]=>
  string(1) "A"
  [4]=>
  string(1) "A"
  [5]=>
  string(1) "B"
  [6]=>
  string(1) "B"
  [7]=>
  string(1) "B"
  [8]=>
  string(1) "B"
  [9]=>
  string(1) "B"
}
PreviousMutexNextGoroutine vs CoroutineGen

Last updated 8 months ago