Description
This function is used to attempt to acquire a lock with a specific name (str). Once a session successfully acquires a lock with a particular name, any other session that attempts to acquire the same-named lock will be blocked (forced to wait) until the original lock holder releases it.
Locks acquired using the GET_LOCK() function can be explicitly released by executing RELEASE_LOCK(). Additionally, when a session terminates, whether normally or abnormally, all locks held by that session are implicitly released.
Notice
The lock obtained by using GET_LOCK() is not released when the transaction is committed or rolled back.
Syntax
GET_LOCK('str', timeout)
Description
Parameters
str: The name of the lock, which is a string.timeout: The timeout period for waiting for the lock to be released, in seconds. Valid values:- The value can be 0 or a positive number.
- It can also be a negative value, indicating that the wait time is infinite. The session will wait indefinitely until it acquires the lock.
Return value
- Return 1: The lock was successfully acquired. The session that called
GET_LOCKnow holds the lock, and any other attempt to acquire the same lock will fail unless the lock is released. - Return 0: indicates that the lock acquisition attempt failed due to a timeout. This usually means the lock has already been acquired by another session and was not released during the timeout period.
- Returns
NULL: An error occurred while attempting to acquire the lock. This may be due to insufficient memory or the thread attempting to acquire the lock being forcibly terminated.
Examples
In session 1, execute the following command to attempt to acquire the lock named
my_lock, with a maximum wait of 10 seconds.obclient [(none)]> SELECT GET_LOCK('my_lock', 10);The return result is as follows:
+-------------------------+ | GET_LOCK('my_lock', 10) | +-------------------------+ | 1 | +-------------------------+ 1 row in setA return value of 1 indicates that the lock
my_lockhas been successfully acquired.In session 2, execute the following command to attempt to acquire the lock named
my_lock, with a maximum wait of 10 seconds.obclient [(none)]> SELECT GET_LOCK('my_lock', 10);The return result is as follows:
+-------------------------+ | GET_LOCK('my_lock', 10) | +-------------------------+ | 0 | +-------------------------+ 1 row in setA return result of 0 indicates that the attempt to acquire lock
my_lockfailed due to a timeout.