Repository navigation
Expand file tree
/
Copy pathbarrier.php
More file actions
executable file
·49 lines (39 loc) · 1.76 KB
/
Copy pathbarrier.php
File metadata and controls
executable file
·49 lines (39 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/usr/bin/env php
<?php
declare(strict_types=1);
/**
* This example shows how to wait for a collection of coroutines to finish in PHP applications. It has 3 coroutines
* executed, and takes about 3 seconds to finish.
*
* Class \Swoole\Coroutine\Barrier is defined in this file:
* https://github.com/swoole/library/blob/master/src/core/Coroutine/Barrier.php
*
* This example uses class \Swoole\Coroutine\Barrier, which is implemented using destruct methods in PHP: each coroutine
* keeps a reference to $barrier through `use ($barrier)`. When a coroutine finishes, its reference is released; when
* the last one is gone, the barrier's destructor wakes up Barrier::wait(). So the `use ($barrier)` is required even
* though the variable isn't used inside the coroutine.
*
* Class \Swoole\Coroutine\Barrier works similarly to class \Swoole\Coroutine\WaitGroup, which is implemented using
* channels (class \Swoole\Coroutine\Channel).
* @see https://github.com/deminy/swoole-by-examples/blob/master/examples/csp/waitgroup.php
*
* How to run this script:
* docker compose exec -t client bash -c "time ./csp/barrier.php"
*/
use Swoole\Coroutine\Barrier;
use function Swoole\Coroutine\go;
use function Swoole\Coroutine\run;
run(function (): void {
$barrier = Barrier::make();
go(function () use ($barrier): void { // @phpstan-ignore closure.unusedUse
sleep(1);
});
go(function () use ($barrier): void { // @phpstan-ignore closure.unusedUse
sleep(2);
});
go(function () use ($barrier): void { // @phpstan-ignore closure.unusedUse
sleep(3);
});
Barrier::wait($barrier); // Wait for those 3 coroutines to finish.
// Any code here won't be executed until all 3 coroutines created in this function finish execution.
});