I have a table named events, which contains in-game events such as construction of buildings, research, etc.. Each event has a timestamp indicating when it completes. Engine: innoDB
Every pageload, the program runs a quick search of the events table for rows where timestamp is in the past (ie. the event has been completed). It selects these rows then deletes them so any other runs don’t see and process the same events.
What I’m worried about is what would happen if two pagelods happened so that both of them read the same rows before one or the other has a chance to delete the read rows, and what if an event happens right between selecting and deleting.
What I’m thinking should fix it is:
SET @now=NOW();
SELECT * FROM `events` WHERE `timestamp` < @now FOR UPDATE
DELETE FROM `events` WHERE `timestamp` < @now
But I’m having some trouble testing it. How would I go about testing whether or not this is working as it should?
Going to answer my own question here :p
Use
sleep()between theselectanddelete, and have two calls at the same time.Final code:
Results:
That’s with the sleep. Without the sleep both end in under 0.002 seconds.