1. 意向锁
https://dev.mysql.com/doc/refman/5.7/en/innodb-locking.html#innodb-insert-intention-locks
官方文档,意向锁是Innodb为了支持多种粒度锁(表锁+行锁)设计的。
举例:
一个表 tab1
id, name
2, "xxxx"
id是unique key。
事务T1 select ... from tab1 where id=2 for update.
事务T2 lock tab1 .... write。
若无意向锁,事务T2需扫描表的每一行,看下是否有锁。
有了意向锁后,T2只需判断与T1的意向锁是否兼容即可。
2. Gap锁
Gap locks in InnoDB are “purely inhibitive”, which means that their only purpose is to prevent other transactions from inserting to the gap. Gap locks can co-exist. A gap lock taken by one transaction does not prevent another transaction from taking a gap lock on the same gap. There is no difference between shared and exclusive gap locks. They do not conflict with each other, and they perform the same function.
3. Next-Key Locks
是Gap锁 与 Record Locks的结合,区间为前开后闭。如一个index 有10, 11, 13, and 20几条记录,则可能存在的Next-Key Locks是:
(negative infinity, 10]
(10, 11]
(11, 13]
(13, 20]
(20, positive infinity)
Next-Key Locks用于RR事务隔离级别,解决幻读问题。
4. insert intention locks
插入意向锁是一种特殊的Gap锁,它不属于上述1. 意向锁,因为意向锁是表锁,而插入意向锁是行锁。
举例:
有一张表
mysql> CREATE TABLE child (id int(11) NOT NULL, PRIMARY KEY(id)) ENGINE=InnoDB;
mysql> INSERT INTO child (id) values (90),(102);
现在事务T1插入id=100,
事务T2插入id=101
则T1,1-获得(90,102)的gap locks, 2-获得id=100的record locks
事务T2,1-获得(90, 102)的gap locks, 2-获得id=101的record locks
两者的插入互不影响。(insert intention locks为解决并发)
但若T1
START TRANSACTION;
SELECT * FROM child WHERE id > 100 FOR UPDATE;
T1的锁包含了(100, 102)的gap锁和 id>100的X锁
此时T2
START TRANSACTION;
INSERT INTO child (id) VALUES (101);
会获得(90, 102)的Gap锁,但会等待id=101的独占锁。
最后,不同的SQL语句对应的锁如下描述:
https://dev.mysql.com/doc/refman/5.7/en/innodb-locks-set.html
注意insert 与insert on duplicate 的区别,即在检测到on duplicate后,insert加一个S锁,而insert on duplicate 在UK加一个X Next-Key locks. 在PK加一个X record locks。
以及死锁产生示例