Shared locks and exclusive locks in MySQL

        Row-level locks are the most granular locks in Mysql. Row-level 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.

Share Lock

Shared locks, also known as read locks, are locks created by read operations. Other users can read the data concurrently, but no transaction can make modifications to 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, but not exclusive locks. Transactions that are granted a shared lock can only read data and cannot modify data.

usage

SELECT ... LOCK IN SHARE MODE;

If it is added after the query statement LOCK IN SHARE MODE, Mysql will add a shared lock to each row in the query result. 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 the table using the shared lock, and these threads are reading the same version of the data.

Exclusive lock (eXclusive Lock)

An exclusive lock is also called a write lock. If transaction T adds an exclusive lock to data A, other transactions cannot add any type of block to A. Transactions granted exclusive locks can both read and modify data.

usage

SELECT ... FOR UPDATE;

After the query statement is added FOR UPDATE, Mysql will add an exclusive lock to each row in the query result. 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.

intent lock

Intent locks are table-level locks designed primarily to reveal the type of lock that the next row will be requested for within a transaction. Two table locks in InnoDB:

Intentional shared lock (IS): Indicates that the transaction is ready to add a shared lock to a data row, that is to say, a data row must first obtain the IS lock of the table before adding a shared lock

Intentional exclusive lock (IX): Similar to the above, it means that the transaction is ready to add an exclusive lock to a data row, indicating that the transaction must obtain the IX lock of the table before adding an exclusive lock to a data row.

Intent locks are automatically added by InnoDB and do not require user intervention.

For insert, update, and delete, InnoDB will automatically add an exclusive lock (X) to the data involved; for general Select statements, InnoDB will not add any locks. Transactions can display shared locks or exclusive locks through the following statements.

Shared lock:SELECT ... LOCK IN SHARE MODE;

Exclusive lock:SELECT ... FOR UPDATE;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324892574&siteId=291194637