Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simultaneous SELECT and UPDATE - Locking to prevent concurrency problems

So I'm working in an environment with high concurrency. What I want to do is select a row from the mysql database based on a certain property and then once I have that row, I want to set a "locked" flag in the row so I can do some work in php (which could take some time) and then unlock it when I'm done. What is the best way to do this in order to prevent concurrency problems that arise when having a separate SELECT and UPDATE command?

like image 885
peter986532 Avatar asked Jul 22 '11 22:07

peter986532


People also ask

How can concurrency problems be prevented?

The main way we can avoid such concurrency issues and build reliable code is to work with immutable objects. This is because their state cannot be modified by the interference of multiple threads. However, we can't always work with immutable objects.

How do you prevent concurrency in a database?

Exclusive Lock (X): For example, if a transaction wants to update some information about a particular stock the database will let them read by placing an exclusive lock. Therefore, when the second transaction wants to read or write, the exclusive lock prevents this operation.

How locks can be implemented to control the concurrency?

DBMS in Simple Steps These are: Binary Locks - These can only be in one of two states, locked or unlocked. Shared/Exclusive Locks - Shared locks are acquired when only read operation is to be performed. Shared locks can be shared between multiple transactions as there is no data being altered.

What happens if two users try to update a database at the same time?

there will be occasions where two users will both read the same data into memory. User 1 will update the data and write those changes back to the database before user 2 does the same thing. Now you have a concurrency control conflict because user 1 read the data before user 2 wrote it back to the database.


1 Answers

using the select for update command : http://dev.mysql.com/doc/refman/5.1/en/innodb-locking-reads.html

like image 117
plague Avatar answered Nov 15 '22 09:11

plague