mysql數據庫中默認的隔離級別為repeat-read.
innodb默認使用了next-gap算法,這種算法結合了index-row鎖和gap鎖。正因為這樣的鎖算法,innodb在可重復讀這樣的默認隔離級別上,可以避免幻象的產生。
innodb_locks_unsafe_for_binlog最主要的作用就是控制innodb是否對gap加鎖。
注意該參數如果是enable的,則是unsafe的,此時gap不會加鎖;反之,如果disable掉該參數,則gap會加鎖。當然對於一些和數據完整性相關的定義,如外鍵和唯一索引(含主鍵)需要對gap進行加鎖,那么innodb_locks_unsafe_for_binlog的設置並不會影響gap是否加鎖。
在5.1.15的時候,innodb引入了一個概念叫做“semi-consistent”,這樣會在innodb_locks_unsafe_for_binlog的狀態為ennable時在一定程度上提高update並發性。
幻讀(Phantom Read): 是指當用戶讀取某一范圍的數據行時,B事務在該范圍內插入了新行,當用戶再讀取該范圍的數據行時,會發現有新的“幻影”行。InnoDB和Falcon存儲引擎通 過多版本並發控制機制解決了幻讀問題。
Consider the following example, beginning with this table:
CREATE TABLE t (a INT NOT NULL, b INT) ENGINE = InnoDB;
INSERT INTO t VALUES (1,2),(2,3),(3,2),(4,3),(5,2);
COMMIT;
In this case, table has no indexes, so searches and index scans use the hidden clustered index for record locking (seeSection 14.8.2.1, “Clustered and Secondary Indexes”).
Suppose that one client performs an UPDATE using these statements:
SET autocommit = 0;
UPDATE t SET b = 5 WHERE b = 3;
Suppose also that a second client performs an UPDATE by executing these statements following those of the first client:
SET autocommit = 0;
UPDATE t SET b = 4 WHERE b = 2;
As InnoDB executes each UPDATE, it first acquires an exclusive lock for each row, and then determines whether to modify it. If InnoDB does not modify the row and innodb_locks_unsafe_for_binlog is enabled, it releases the lock. Otherwise, InnoDBretains the lock until the end of the transaction. This affects transaction processing as follows.
If innodb_locks_unsafe_for_binlog is disabled, the first UPDATE acquires x-locks and does not release any of them:
x-lock(1,2); retain x-lock
x-lock(2,3); update(2,3) to (2,5); retain x-lock
x-lock(3,2); retain x-lock
x-lock(4,3); update(4,3) to (4,5); retain x-lock
x-lock(5,2); retain x-lock
The second UPDATE blocks as soon as it tries to acquire any locks (because the first update has retained locks on all rows), and does not proceed until the first UPDATE commits or rolls back:
x-lock(1,2); block and wait for first UPDATE to commit or roll back
If innodb_locks_unsafe_for_binlog is enabled, the first UPDATE acquires x-locks and releases those for rows that it does not modify:
x-lock(1,2); unlock(1,2)
x-lock(2,3); update(2,3) to (2,5); retain x-lock
x-lock(3,2); unlock(3,2)
x-lock(4,3); update(4,3) to (4,5); retain x-lock
x-lock(5,2); unlock(5,2)
For the second UPDATE, InnoDB does a “semi-consistent” read, returning the latest committed version of each row to MySQL so that MySQL can determine whether the row matches the WHERE condition of the UPDATE:
x-lock(1,2); update(1,2) to (1,4); retain x-lock x-lock(2,3); unlock(2,3) x-lock(3,2); update(3,2) to (3,4); retain x-lock x-lock(4,3); unlock(4,3) x-lock(5,2); update(5,2) to (5,4); retain x-lock
---------------------
作者:彭薄
來源:CSDN
原文:https://blog.csdn.net/cxl0921/article/details/77623439
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!