Purpose
GET_LOCK() tries to obtain a lock with a name given by the string str. When a session successfully obtains a lock with a specific name, any other sessions attempting to obtain a lock with the same name will be blocked (that is, forced to wait) until the session holding the lock releases it.
You can use RELEASE_LOCK() to explicitly release a lock obtained with GET_LOCK(). In addition, when a session terminates, whether normally or abnormally, all locks held by the session are released implicitly.
Notice
Locks obtained with GET_LOCK() are not released when transactions commit or roll back.
Syntax
GET_LOCK('str', timeout)
Description
Parameters
str: the name of the lock. The value is a string.timeout: the timeout period for waiting a lock to be released, in seconds. The valid values are as follows:- 0 or a positive number.
- A negative number, indicating that the session will wait indefinitely until the lock is obtained.
Return value
1: The lock was obtained successfully. The session that called theGET_LOCK()function is then holding the lock. Any other attempts to obtain a lock with the same name will not succeed unless the lock is released.0: The attempt to obtain the lock failed due to a timeout. This usually means that the lock is held by another session and not released within the timeout period.NULL: An error occurred while attempting to obtain the lock, which may be because the memory is insufficient or the thread for obtaining the lock is forcibly terminated.
Examples
In session 1, run the following command to obtain the lock named
my_lockin a timeout of 10s:obclient [(none)]> SELECT GET_LOCK('my_lock', 10);The return result is as follows:
+-------------------------+ | GET_LOCK('my_lock', 10) | +-------------------------+ | 1 | +-------------------------+ 1 row in set1is returned, indicating that the session has obtained themy_locklock.In session 2, run the following command to obtain the lock named
my_lockin a timeout of 10s:obclient [(none)]> SELECT GET_LOCK('my_lock', 10);The return result is as follows:
+-------------------------+ | GET_LOCK('my_lock', 10) | +-------------------------+ | 0 | +-------------------------+ 1 row in set0is returned, indicating that the attempt to obtain themy_locklock failed due to a timeout.