If a duplicate-key error occurs, a shared lock on the duplicate index record is set. This use of a shared lock can result in deadlock should there be multiple sessions trying to insert the same row if another session already has an exclusive lock. This can occur if another session deletes the row.
與在文檔的例子中去,
假設一個InnoDB表T1具有以下結構:
CREATE TABLE t1 (i INT, PRIMARY KEY (i)) ENGINE = InnoDB;
現在假設三個會話按順序執行以下操作:
會話1:
START TRANSACTION;
INSERT INTO t1 VALUES(1);
會話2:
START TRANSACTION;
INSERT INTO t1 VALUES(1);
第三節:
START TRANSACTION;
INSERT INTO t1 VALUES(1);
會議1:
ROLLBACK;
The first operation by session 1 acquires an exclusive lock for the row. The operations by sessions 2 and 3 both result in a duplicate-key error and they both request a shared lock for the row. When session 1 rolls back, it releases its exclusive lock on the row and the queued shared lock requests for sessions 2 and 3 are granted. At this point, sessions 2 and 3 deadlock: Neither can acquire an exclusive lock for the row because of the shared lock held by the other.
我有一些問題:
1)插入查詢對它插入的行採用排它鎖。因此,假設T1正在插入第1行,它將鎖定第1行。現在當T2寫入時,INNODB將在執行之前評估該查詢並發現它將寫入相同的PK(i = 1的行)並讓T2等待?或者它會開始執行T2,並發現它給出了重複的鍵錯誤或PK違例。
2)爲什麼T2和T3共享鎖?插入過程中共享鎖如何進入畫面?
添加一些'睡眠(10)'函數調用進行測試的情況下。那麼我們可以進一步討論。包括'SHOW ENGINE INNODB STATUS;'的相關部分。 –