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"
}

Last updated