在我們執(zhí)行事務(wù)t1的 insert 時(shí),沒有在任何鎖的斷點(diǎn)處出現(xiàn),這跟 MySQL 插入的原理有關(guān)系
insert 加的是隱式鎖。什么是隱式鎖?隱式鎖的意思就是沒有鎖
在 t1 插入記錄時(shí),是不加鎖的。這個(gè)時(shí)候事務(wù) t1 還未提交的情況下,事務(wù) t2 嘗試插入的時(shí)候,發(fā)現(xiàn)有這條記錄,t2 嘗試獲取 S 鎖,會(huì)判定記錄上的事務(wù) id 是否活躍,如果活躍的話,說明事務(wù)未結(jié)束,會(huì)幫 t1 把它的隱式鎖提升為顯式鎖( X 鎖)
源碼如下
t2 獲取S鎖的結(jié)果:DB_LOCK_WAIT
實(shí)驗(yàn)2:
批量插入順序不一致的導(dǎo)致的死鎖
t1
t2
begin
insert into t1(a, b)values("1", "1");
成功
insert into t1(a, b)values("2", "2");
成功
insert into t1(a, b)values("2", "2");
t1 嘗試獲取 S 鎖,把 t2 的隱式鎖提升為顯式 X 鎖,進(jìn)入 DB_LOCK_WAIT
insert into t1(a, b)values("1", "1");
t2 嘗試獲取 S 鎖,把 t1 的隱式鎖提升為顯式 X 鎖,產(chǎn)生死鎖
------------------------
LATEST DETECTED DEADLOCK
------------------------
181101 9:48:36
*** (1) TRANSACTION:
TRANSACTION 3309, ACTIVE 215 sec inserting
mysql tables in use 1, locked 1
LOCK WAIT 3 lock struct(s), heap size 376, 2 row lock(s), undo log entries 2
MySQL thread id 2, OS thread handle 0x70000a845000, query id 58 localhost root update
insert into t1(a, b)values("2", "2")
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 55 page no 4 n bits 72 index `uk_name` of table `d1`.`t1` trx id 3309 lock mode S waiting
Record lock, heap no 3 PHYSICAL RECORD: n_fields 3; compact format; info bits 0
0: len 1; hex 32; asc 2;;
1: len 1; hex 32; asc 2;;
2: len 4; hex 80000002; asc ;;
*** (2) TRANSACTION:
TRANSACTION 330A, ACTIVE 163 sec inserting
mysql tables in use 1, locked 1
3 lock struct(s), heap size 376, 2 row lock(s), undo log entries 2
MySQL thread id 3, OS thread handle 0x70000a888000, query id 59 localhost root update
insert into t1(a, b)values("1", "1")
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 55 page no 4 n bits 72 index `uk_name` of table `d1`.`t1` trx id 330A lock_mode X locks rec but not gap
Record lock, heap no 3 PHYSICAL RECORD: n_fields 3; compact format; info bits 0
0: len 1; hex 32; asc 2;;
1: len 1; hex 32; asc 2;;
2: len 4; hex 80000002; asc ;;
*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 55 page no 4 n bits 72 index `uk_name` of table `d1`.`t1` trx id 330A lock mode S waiting
Record lock, heap no 2 PHYSICAL RECORD: n_fields 3; compact format; info bits 0
0: len 1; hex 31; asc 1;;
1: len 1; hex 31; asc 1;;
2: len 4; hex 80000001; asc ;;
*** WE ROLL BACK TRANSACTION (2)