Among the row-level locks, table-level locks and page-level locks in MySQL, we have introduced that row-level locks are the most granular locks in MySQL. Row-level locks Locks can greatly reduce conflicts in database operations. Row-level locks are divided into shared locks and exclusive locks. This article will introduce the concepts, usage and precautions of shared locks and exclusive locks in detail.
Shared lock, also known as read lock, is a lock created by a read operation. Other users can read the data concurrently, but no transaction can modify the data (acquire an exclusive lock on the data) until all shared locks have been released.
If transaction T
adds a shared lock to data A
, other transactions can only add shared locks to A
and cannot add exclusive locks. . Transactions that are granted shared locks can only read data and cannot modify data.
Usage
##SELECT ... LOCK IN SHARE MODE;
LOCK IN after the query statement SHARE MODE, MySQL will add a shared lock to each row in the query result set. When no other thread uses an exclusive lock on any row in the query result set, it can successfully apply for a shared lock, otherwise it will be blocked. Other threads can also read tables using shared locks, and these threads read the same version of data.
T adds exclusive lock to data
A , then other transactions can no longer add any type of blockade to
A. Transactions granted exclusive locks can both read and modify data.
Usage
SELECT ... FOR UPDATE;
FOR UPDATE## after the query statement #, MySQL will add an exclusive lock to each row in the query result set. When no other thread uses an exclusive lock on any row in the query result set, it can successfully apply for an exclusive lock, otherwise it will be blocked. Intention Lock (Intention Lock)
lock of the table;
lock on the table.
For
INSERT, UPDATE
and DELETE
, InnoDB will automatically add exclusive locks to the data involved; for general SELECT
statement, InnoDB will not add any locks, transactions can explicitly add shared locks or exclusive locks through the following statements. Shared lock:
Exclusive lock:
The above is the detailed content of Share the usage of shared locks and exclusive locks in MySQL. For more information, please follow other related articles on the PHP Chinese website!