3 coroutines, 2 pooled connections — automatic management via $stmt and transactions

Code — one PDO with pool, 3 coroutines
// Single PDO object with a pool of 2 connections
$pdo = new PDO($dsn, $user, $pass, [
PDO::ATTR_POOL_ENABLED => true,
PDO::ATTR_POOL_MAX => 2,
]);
for ($i = 1; $i <= 3; $i++) {
spawn(function() use ($pdo, $i) {
// prepare() auto-acquires conn from pool
$stmt = $pdo->prepare("SELECT * FROM users WHERE id=?");
$stmt->execute([$i]); // waits for DB
$user = $stmt->fetch();
processUser($user);
// $stmt goes out of scope -> refcount=0
// conn auto-returns to pool!
});
}
PDO Pool (ATTR_POOL_MAX: 2)
🔌
Connection #1
available
🔌
Connection #2
available
Wait queue:
empty
Coroutine 1
ready
Coroutine 2
ready
Coroutine 3
ready
Execution Timeline 0 ms
Coroutine 1
Coroutine 2
Coroutine 3
015304555ms
CPU working
Waiting for DB
Waiting for pool
0 ms
Total time
0 ms
DB wait
0 ms
Pool wait
0 ms
Time saved

Click "Play" to start

This visualization shows how the PDO connection pool automatically manages resources. A connection is pinned while $stmt exists or a transaction is active. When $stmt is destroyed and there's no transaction, the connection automatically returns to the pool.