<?php
function coroutine1() {
for ($i = 1; $i <= 5; $i++) {
echo "coroutine1: {$i}\n";
yield;
}
}
function coroutine2() {
for ($i = 1; $i <= 10; $i++) {
echo "coroutine2: {$i}\n";
$loop = yield;
if ($i == 3) {
echo "coroutine2 spawning coroutine3\n";
$loop->enqueue("#3", coroutine3());
}
}
}
function coroutine3() {
for ($i = 1; $i <= 5; $i++) {
echo "coroutine3: {$i}\n";
yield;
}
}
class EventLoop {
private $tasks = [];
public function enqueue($key, Generator $task) {
$this->tasks[$key] = $task;
}
public function run() {
foreach ($this->tasks as $key => $task) {
$task->send($this);
if (!$task->valid()) {
echo "task {$key} complete\n";
unset($this->tasks[$key]);
}
}
return !empty($this->tasks);
}
}
$loop = new EventLoop();
$loop->enqueue("#1", coroutine1());
$loop->enqueue("#2", coroutine2());
while ($loop->run());
- Output for 7.2.0 - 7.2.34, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.4, 8.3.6 - 8.3.7
- coroutine1: 1
coroutine1: 2
coroutine2: 1
coroutine2: 2
coroutine1: 3
coroutine2: 3
coroutine1: 4
coroutine2 spawning coroutine3
coroutine2: 4
coroutine1: 5
coroutine2: 5
coroutine3: 1
coroutine3: 2
task #1 complete
coroutine2: 6
coroutine3: 3
coroutine2: 7
coroutine3: 4
coroutine2: 8
coroutine3: 5
coroutine2: 9
task #3 complete
coroutine2: 10
task #2 complete
- Output for 8.3.5
- Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
coroutine1: 1
coroutine1: 2
coroutine2: 1
coroutine2: 2
coroutine1: 3
coroutine2: 3
coroutine1: 4
coroutine2 spawning coroutine3
coroutine2: 4
coroutine1: 5
coroutine2: 5
coroutine3: 1
coroutine3: 2
task #1 complete
coroutine2: 6
coroutine3: 3
coroutine2: 7
coroutine3: 4
coroutine2: 8
coroutine3: 5
coroutine2: 9
task #3 complete
coroutine2: 10
task #2 complete
preferences:
175.32 ms | 403 KiB | 184 Q