Two coroutines efficiently share CPU time

Coroutine 1 — User Processing Iteration: 0/3
$coro1 = spawn(function() {
$pdo = new PDO($dsn);
foreach ([1,2,3] as $id) {
$stmt = $pdo->prepare("SELECT * FROM users WHERE id=?");
$stmt->execute([$id]); // ⏳ 15ms
$user = $stmt->fetch();
processUser($user);
}
});
Coroutine 2 — Logging + Notifications Iteration: 0/3
$coro2 = spawn(function() {
$pdo = new PDO($dsn);
$socket = fsockopen($host, 9000);
foreach (['login','click','logout'] as $e) {
$stmt = $pdo->prepare("INSERT INTO logs VALUES(?)");
$stmt->execute([$e]); // ⏳ 12ms
fwrite($socket, $e); // ⏳ 20ms
}
});
Execution Timeline 0 ms
Coroutine 1 ready
Coroutine 2 ready
0255075100ms
CPU:
Waiting
CPU working
Waiting for DB
Waiting for network
0 ms
Total time
0 ms
DB wait
0 ms
Network wait
0 ms
Time saved

Click "Play" to start

This visualization shows how two coroutines efficiently share the CPU. While one waits for a response from the database or network, the other does useful work. This is cooperative multitasking.