Native MySQL locking doesn't provide this functionality. You could use a column to perform your "locks".
Assuming each thread had a unique ID, you could create a column named thread_owner
, with default 0.
One thread would grab a row like this:
UPDATE mytable
SET thread_owner = :my_threadID
WHERE thread_owner = 0
LIMIT 1
Then select the row like this (it might return none, if there were no rows to be processed):
SELECT *
FROM mytable
WHERE thread_owner = :my_threadID
Then process it, and finally delete it.
This solution would work on both MyISAM and InnoDB.
However, for InnoDB, it might be slow because each UPDATE statement is trying to lock all rows where thread_owner = 0, and unless you're sure you're locking all rows in the same order each time, it could even cause a deadlock. So, you might try explicitly locking the whole table in your UPDATE statement:
LOCK TABLES mytable WRITE;
UPDATE mytable
SET thread_owner = :my_threadID
WHERE thread_owner = 0
LIMIT 1;
UNLOCK TABLES;
That way, both MyISAM and InnoDB will work the same way.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…