Locking case of MySQL different isolation levels

Lock Category

I have talked about before, Lock divided into two categories, one is optimistic locking, one pessimistic locking. Not explain in detail here. Lock mechanism different size This section explains MySQL at different isolation levels, the use of.

Note that the first situation, no matter what level of isolation under, if there is an index, lock are added to the index, but at different levels of isolation, supported by the lock granularity just not the same; lock granularity smaller consumption the more resources. Without an index, the table lock is locked, i.e. lock clustered indexes all rows.

Under lock isolation level

RR isolation level is repeatable read. REPEATABLE READ.

RC isolation level is read committed. READ COMMITTED.

First build table and insert the data, as follows.

CREATE TABLE 'blog'(
   'id' BIGINT(20) NOT NULL,
   'name' VARCHAR(16) COLLATE utf8mb4_bin DEFAULT NULL,
   'idcard' BIGINT(20) NOT NULL,
   PRIMARY KEY('id')
) ENGINE=InnoDB DEFAULT CHARSET = utf8mb4 COLLATE=utf8mb4_bin;
-- 插入数据
INSERT INTO blog VALUES(1,'test1',100),(5,'blog',200),(8,'blog',300),(10,'test2',400);

If an exact match, such as updating primary key. Whether in the RR or in the RC isolation level, row locks will always hit on a clustered index, which is divided into two cases, if the following two conditions, respectively, are added to X lock on the line index and S lock.

//在id=1的聚簇索引上加X锁
UPDATE blog SET name = 'x' WHERE id = 1;
//在id=1的聚簇索引上加S锁
SELECT * FROM blog WHERE id = 1 LOCK IN SHARE MODE;

If the scope of the query, and if, it will lock on the clustered index row hit in the RC isolation level, the next level because there is no gap in the RC lock isolation, so there will be phantom read phenomenon. Because in RR isolation mode, using the gap lock to solve the problem of phantom read, so, if it is in the RR isolation mode, will be added next-key locks (locked rows and gaps) in the clustered index row all hit. After a record index last hit, it will be combined with next-key lock.

//在RC隔离级别下,在id=8和10的聚簇索引上加X锁
//在RR隔离级别下,在id=8、(10,+)的聚簇索引上加X锁
//在(5,8)(8,10)(10,+)加间隙锁
UPDATE blog SET name = 'test3' WHERE id > 7;
//在RC隔离级别下,在id=1的聚簇索引上加X锁
//在RR隔离级别下,在id=1、5的聚簇索引上加X锁
//在RR隔离级别下,在(-,1)(1,5)加间隙锁
UPDATE blog SET name = 'test4' WHERE id <=1;

If you find the content is empty, that did not hit a clustered index, then under RC isolation level, nothing will lock, but in the RR isolation level, will find space to lock the target is located.

Published 12 original articles · won praise 2 · Views 669

Guess you like

Origin blog.csdn.net/gonghaiyu/article/details/104307527