GET_LOCK
Syntax
GET_LOCK(str,timeout)
Description
Tries to obtain a lock with a name given by the string str
, using a timeout of
timeout
seconds. Returns 1
if the lock was obtained
successfully, 0
if the attempt timed out (for example,
because another client has previously locked the name), or
NULL
if an error occurred (such as running out of memory or
the thread was killed with mysqladmin kill).
If you have a lock obtained with
GET_LOCK()
, it is released when you execute RELEASE_LOCK(), execute a new GET_LOCK()
,
or your connection terminates (either normally or abnormally). Locks obtained
with GET_LOCK()
do not interact with transactions. That is,
committing a transaction does not release any such locks obtained during the
transaction.
MariaDB starting with 10.0.2
Konstantin "Kostja" Osipov
contributed a patch (MDEV-3917) which
allows a user to set many user-level locks in one connection with the
GET_LOCK()
call. If a deadlock is detected, GET_LOCK()
returns an error. If a lock is not needed anymore, remember to release it before calling GET_LOCK()
again.
str
is case insensitive for GET_LOCK()
and related functions. If str
is an empty string or NULL
, GET_LOCK()
returns NULL
and does nothing. timeout
is rounded to the closest integer.
This function can be used to implement application locks or to simulate record
locks. Names are locked on a server-wide basis. If a name has been locked by
one client, GET_LOCK()
blocks any request by another client
for a lock with the same name. This allows clients that agree on a given lock
name to use the name to perform cooperative advisory locking. But be aware that
it also allows a client that is not among the set of cooperating clients to
lock a name, either inadvertently or deliberately, and thus prevent any of the
cooperating clients from locking that name. One way to reduce the likelihood of
this is to use lock names that are database-specific or application-specific.
For example, use lock names of the form db_name.str
or
app_name.str
.
Examples
SELECT GET_LOCK('lock1',10)\G *************************** 1. row *************************** GET_LOCK('lock1',10): 1 SELECT IS_FREE_LOCK('lock2')\G *************************** 1. row *************************** IS_FREE_LOCK('lock2'): 1 SELECT GET_LOCK('lock2',10)\G *************************** 1. row *************************** GET_LOCK('lock2',10): 1 SELECT RELEASE_LOCK('lock2')\G *************************** 1. row *************************** RELEASE_LOCK('lock2'): 1 SELECT RELEASE_LOCK('lock1')\G *************************** 1. row *************************** RELEASE_LOCK('lock1'): NULL