Purpose
This function is used to attempt to obtain a lock with a specific name (str). Once a session successfully obtains a lock with a specific name, any other session attempting to obtain a lock with the same name will be blocked (i.e., forced to wait) until the session that originally held the lock releases it.
Locks obtained using the GET_LOCK() function can be explicitly released by executing RELEASE_LOCK(). Additionally, locks held by a session are implicitly released when the session terminates, whether it ends normally or abnormally.
Notice
Locks obtained using GET_LOCK() are not released upon transaction commit or rollback.
Syntax
GET_LOCK('str', timeout)
Purpose
Parameters
str: Specifies the name of the lock, which is a string.timeout: Specifies the timeout period (in seconds) for waiting for the lock to be released. Valid values are as follows:- It can be 0 or a positive number.
- It can also be a negative number, indicating an infinite wait time. In this case, the session will wait indefinitely until the lock is obtained.
Return value
- Returns 1: Indicates that the lock was successfully obtained. At this point, the session that called
GET_LOCKholds the lock, and any subsequent attempts to obtain the same lock will fail unless the lock is released. - Returns 0: Indicates that the attempt to obtain the lock failed due to a timeout. This usually means that the lock was obtained by another session and was not released within the timeout period.
- Returns
NULL: Indicates an error occurred while attempting to obtain the lock. This could be due to insufficient memory or the thread attempting to obtain the lock being forcibly terminated.
Examples
In session 1, execute the following command to attempt to obtain a lock named
my_lock, waiting up to 10 seconds.obclient [(none)]> SELECT GET_LOCK('my_lock', 10);The result is as follows:
+-------------------------+ | GET_LOCK('my_lock', 10) | +-------------------------+ | 1 | +-------------------------+ 1 row in setThe result is 1, indicating that the lock
my_lockwas successfully obtained.In session 2, execute the following command to attempt to obtain a lock named
my_lock, waiting up to 10 seconds.obclient [(none)]> SELECT GET_LOCK('my_lock', 10);The result is as follows:
+-------------------------+ | GET_LOCK('my_lock', 10) | +-------------------------+ | 0 | +-------------------------+ 1 row in setThe result is 0, indicating that the attempt to obtain the lock
my_lockfailed due to a timeout.
