> For the complete documentation index, see [llms.txt](https://venndev.gitbook.io/vapm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://venndev.gitbook.io/vapm/coroutinegen/mutex/example.md).

# Example

```php
<?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"
}
```
