Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly avoid Mysql Race Conditions

I know this has been asked before, but I'm still confused and would like to avoid any problems before I go into programming if possible.

I plan on having an internal website with at least 100 users active at any given time. Users would post an item (inserted into db with a 0 as its value) and that item would be shown via a php site (db query). Users then get the option to press a button and lock that item as theirs (assign the value of that item as their id)

How do I ensure that 2 or more users don't retrieve the same item at the same time. I know in programming like c++ I would just use plain ol mutex lock. Is their an equivalent in mysql where it will lock just one item entry like that? I've seen references to LOCK_TABLES and GET_LOCK and many others so I'm still very confused on what would be best.

There is potential for many people all racing to press that one button and it would be disastrous if multiple people get a confirmation.

I know this is a prime example of a race condition, but mysql is foreign territory for me.

I obviously will query the value of the item before I update it and make sure it hasn't written, but what is the best way to ensure that this race condition is avoided.

Thanks in advance.

like image 284
user1911736 Avatar asked Oct 06 '22 15:10

user1911736


1 Answers

To achieve this, you will need to lock the record somehow. Add a column LockedBy defaulting to 0.

When someone pushes the button execute a query resembling this:

UPDATE table SET LockedBy= WHERE LockedBy=0 and id=;

After the update verify the affected rows (in php mysql_affected_rows). If the value is 0 it means the query did not update anything because the LockedBy column is not 0 and thus locked by someone else.

Hope this helps

like image 58
Gaëtan Avatar answered Oct 10 '22 03:10

Gaëtan