-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfibers.php
More file actions
49 lines (41 loc) · 1.11 KB
/
fibers.php
File metadata and controls
49 lines (41 loc) · 1.11 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
<?php
declare(strict_types=1);
//Not real async operations
$fiber = new Fiber(function (): void {
echo "Fiber started<br/>";
$value = Fiber::suspend("Suspending...");
echo "Fiber resumed with value: $value<br>";
});
echo "Starting fiber ... <br>";
$value = $fiber->start();
echo "Fiber suspended, returned value: $value<br>";
$fiber->resume("Hello from resume");
echo "Fiber has completed<br><br>";
function asyncTask(): Fiber
{
return new Fiber(function (): void {
echo "Doing async work...<br>";
Fiber::suspend();
echo "Resuming work... <br><br>";
});
}
$fiber = asyncTask();
$fiber->start();
echo 'doing another async task <br>';
$fiber->resume();
//Make API calls with rate limiting
$apiCaller = new Fiber(function (): string {
$queries = ['products', 'users', 'orders'];
foreach ($queries as $query) {
echo "Fetched $query data<br>";
Fiber::suspend();
}
return "All API calls done!";
});
$apiCaller->start();
while (!$apiCaller->isTerminated()) {
echo 'other operations<br>';
sleep(1);
$apiCaller->resume();
}
echo $apiCaller->getReturn();