setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = array( 'CREATE TABLE IF NOT EXISTS locktest (item TEXT UNIQUE)', ); foreach($sql as $line) $db->exec($line); $insert = $db->prepare("INSERT OR REPLACE INTO locktest (item) VALUES (?)"); $select = $db->prepare("SELECT COUNT(*) FROM locktest"); while(true) { $db->beginTransaction(); echo "Got lock\n"; $end = microtime(true) + rand(2, 3); while(microtime(true) < $end) { // uncomment these two lines for failure #$select->execute(); #$data = $select->fetchAll(); $insert->execute(array(rand(0,1000))); $select->execute(); $data = $select->fetchAll(); } $db->commit(); echo "Released lock\n"; // if we dont sleep then the race winner holds the lock until it exits while the other blocks usleep(100000); }