二、初始化数据画图 本死锁的堵塞主要集中在二级索引中,我们将二级索KEY idxa ( a )和主键的数据按照Innodb引擎存储的方式大概排列一下则如图:
三、T2 步骤1 T2 步骤1:delete from ty where a=5;
-----TRX NO:334719 LOCK STRUCT(1)(Add by gaopeng) RECORD LOCKS space id 653 page no 4 n bits 72 index idxa of table `test`.`ty` trx id 334719 lock_mode X(LOCK_X) locks gap and rec(LOCK_ORDINARY[next_key_lock]) Record lock, heap no 3 PHYSICAL RECORD: n_fields 2; compact format; info bits 32 0: len 4; hex 80000005; asc ;; 1: len 4; hex 80000009; asc ;; -----TRX NO:334719 LOCK STRUCT(1)(Add by gaopeng) RECORD LOCKS space id 653 page no 3 n bits 72 index PRIMARY of table `test`.`ty` trx id 334719 lock_mode X(LOCK_X) locks rec but not gap(LOCK_REC_NOT_GAP)
四、T1 步骤2 T2 步骤1:delete from ty where a=5; 堵塞
-----TRX NO:334724 LOCK STRUCT(1)(Add by gaopeng) RECORD LOCKS space id 653 page no 4 n bits 72 index idxa of table `test`.`ty` trx id 334724 lock_mode X(LOCK_X) locks gap and rec(LOCK_ORDINARY[next_key_lock]) waiting(LOCK_WAIT) Record lock, heap no 3 PHYSICAL RECORD: n_fields 2; compact format; info bits 32 0: len 4; hex 80000005; asc ;; 1: len 4; hex 80000009; asc ;; 根据这个记录我们可以画图如下,黄色部分为事务T1准备上锁但是被堵塞的部分,包含黄色部分和红色部分的记录说明它既被T2锁定了并且T1拿不到这条记录的锁,它实际上就是一个next key lock的堵塞:
五、T2步骤3 这一步如果是: insert into ty(a,b) values(2,10); 则发生死锁,实际上这一条记录记录在二级索引的值为(2,11),11是主键的值,则画图如下:
MySQL:Innodb 一个死锁案例 image.png
这种情况下则T2也被堵塞,因为这个区域T1也处于堵塞下,则发生死锁。死锁记录如下:
*** (2) WAITING FOR THIS LOCK TO BE GRANTED: RECORD LOCKS space id 653 page no 4 n bits 72 index idxa of table `test`.`ty` trx id 334712 lock_mode X(LOCK_X) locks gap before rec(LOCK_GAP) insert intention(LOCK_INSERT_INTENTION) waiting(LOCK_WAIT) Record lock, heap no 3 PHYSICAL RECORD: n_fields 2; compact format; info bits 32 0: len 4; hex 80000005; asc ;; 1: len 4; hex 80000009; asc ;; 及插入印象锁堵塞