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