测试环境:MySQL 5.7.26 创建测试表:
create table t5(id int); Query OK, 0 rows affected (0.01 sec)
插入测试数据:
mysql> insert into t5 values(1); Query OK, 1 row affected (0.00 sec)
模拟死锁过程:
会话1申请X锁,等待会话2,会话2申请X锁,等待会话1。会话2死锁后回滚并抛出:ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction
此次测试将update改为delete会得到同样的效果。
死锁说明:
死锁日志:
LATEST DETECTED DEADLOCK ------------------------ 2020-08-21 19:00:58 0x7f390fe40700 *** (1) TRANSACTION: TRANSACTION 26178717, ACTIVE 32 sec fetching rows mysql tables in use 1, locked 1 LOCK WAIT 4 lock struct(s), heap size 1136, 3 row lock(s) MySQL thread id 209, OS thread handle 139882660706048, query id 3867249 localhost root updating update t5 set id=2 where id=1 *** (1) WAITING FOR THIS LOCK TO BE GRANTED: RECORD LOCKS space id 835 page no 3 n bits 72 index GEN_CLUST_INDEX of table `test`.`t5` trx id 26178717 lock_mode X locks rec but not gap waiting Record lock, heap no 2 PHYSICAL RECORD: n_fields 4; compact format; info bits 0 0: len 6; hex 0000043d1901; asc = ;; 1: len 6; hex 0000018f7360; asc s`;; 2: len 7; hex ee000016d10110; asc ;; 3: len 4; hex 80000001; asc ;; *** (2) TRANSACTION: TRANSACTION 26178726, ACTIVE 16 sec starting index read, thread declared inside InnoDB 5000 mysql tables in use 1, locked 1 4 lock struct(s), heap size 1136, 2 row lock(s) MySQL thread id 208, OS thread handle 139883056465664, query id 3867266 localhost root updating update t5 set id=2 where id=1 *** (2) HOLDS THE LOCK(S): RECORD LOCKS space id 835 page no 3 n bits 72 index GEN_CLUST_INDEX of table `test`.`t5` trx id 26178726 lock mode S locks rec but not gap Record lock, heap no 2 PHYSICAL RECORD: n_fields 4; compact format; info bits 0 0: len 6; hex 0000043d1901; asc = ;; 1: len 6; hex 0000018f7360; asc s`;; 2: len 7; hex ee000016d10110; asc ;; 3: len 4; hex 80000001; asc ;; *** (2) WAITING FOR THIS LOCK TO BE GRANTED: RECORD LOCKS space id 835 page no 3 n bits 72 index GEN_CLUST_INDEX of table `test`.`t5` trx id 26178726 lock_mode X locks rec but not gap waiting Record lock, heap no 2 PHYSICAL RECORD: n_fields 4; compact format; info bits 0 0: len 6; hex 0000043d1901; asc = ;; 1: len 6; hex 0000018f7360; asc s`;; 2: len 7; hex ee000016d10110; asc ;; 3: len 4; hex 80000001; asc ;; *** WE ROLL BACK TRANSACTION (2)
