I'm trying to do MySQL locks implementation in PHP (I need both shared and exclusive, so I can't use GET LOCK).
<?php
$conn = new \Pdo('mysql:host=localhost;dbname=locks', 'root', 'root', [\PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$conn->exec('INSERT IGNORE INTO locksPoc (lockName) VALUES ("mylock")');
$conn->exec('set session innodb_lock_wait_timeout = 1');
$this->dump('Lock exists in DB');
$conn->beginTransaction();
$rows = $conn->query('SELECT * FROM locksPoc WHERE lockName="mylock" FOR UPDATE');
$row = $rows->fetchAll();
$this->dump('Got the lock');
sleep(30);
$conn->commit();
When I run it in parallel like this:
$ php db.php &
$ php db.php &
It does not work as expected. The second one outputs "Lock exists in DB" immediately but then proceeds to wait 30s before the other script is finished. My expectation was that it will fail after 1s with exception because of the lock timeout.
SHOW VARIABLES LIKE '%timeout';
– GlitterySHOW CREATE TABLE locksPoc
-- we need to see thatlockName
has a unique index (or PK). – Glitterysleep(10); after the
INSERT`. This should make sure of how the processes are aligned. – Glittery