Interactive

How Coroutines Work

Two coroutines efficiently share CPU time: while one waits for the database or network, the other does useful work.

Coroutine 1 · User ProcessingIteration: 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 & NotificationsIteration: 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

CPU: Working0 ms
CPU
Coroutine 1
Coroutine 2
0255075100
Speed
CPU workingCPU (coro 2)Waiting for DBWaiting for network
0 ms
Total time
0 ms
DB wait
0 ms
Network wait
0 ms
Time saved

Cooperative multitasking

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, and no thread ever blocks. Compared to sequential execution (162 ms), cooperative scheduling finishes the same work in 108 ms.