Monday, July 11, 2011

Mutexes or Locking in MySQL


I ran across this feature in MySQL for a project where we needed the ability to ensure that only a single process was updating an entire MySQL database server at one point in time.  We also had to provide this assurance across servers and possibly across servers at multiple locations.
MySQL in fact offers a function called GET_LOCK( str lock_name, num timeout) as well as RELEASE_LOCK(str lock_name).  If no other process curently have a lock identified by the name provided, MySQL returns a '1' indicating the lock attempt was successful.


mysql> select get_lock('abc', 10); 
+---------------------+ 
| get_lock('abc', 10) | 
+---------------------+ 
| 1 | 
+---------------------+
1 row in set (0.04 sec)

Once locked, no other process can obtain a lock using that lock name until the process holding the lock releases it (using RELEASE_LOCK) or exits and disconnects from MySQL (whether on its own or abnormally).  When executing the GET_LOCK SQL where the lock is not free, the SQL enters a continuous re-try loop attempting to obtain the lock for a duration equal to the timeout specified.  If not sucessful, the SQL returns '0' which is of course very easy to check as a result.

mysql> select get_lock('abc', 10); 
+---------------------+ 
| get_lock('abc', 10) | 
+---------------------+ 
| 0 | 
+---------------------+ 
1 row in set (10.00 sec)

This capability provded to be all that we needed to build a simple yet elegant way to ensure only a single process could be operating on the database at any given point in time.  In addition, the unancipated exception that might cause our process to die would not hold the lock thus allowing subsequent processes the ability to continue on.

No comments:

Post a Comment