MySQL 的開放式並行存取控制Optimistic concurrency control

來源:互聯網
上載者:User

標籤:

預設情況下, MySQL的Innodb交易隔離等級是重複讀 repeatable read,

SELECT @@GLOBAL.tx_isolation, @@tx_isolation;
REPEATABLE-READ    REPEATABLE-READ

進行以下測試, 同時開兩個session, S1 和 S2, 都將autocommit關掉

set autocommit=0;

測試使用的是一張簡單的表, 只有一行資料

CREATE TABLE `t1` (  `v1` tinyint(2) NOT NULL DEFAULT ‘0‘,  `v2` tinyint(2) NOT NULL DEFAULT ‘0‘,  `version` mediumint(8) NOT NULL DEFAULT ‘0‘,  PRIMARY KEY (`v1`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;row: 1    1    0

01 - S1 執行 select * from t1; 看到1, 1, 0
02 - S2 執行 select * from t1; 看到1, 1, 0
03 - S2 執行 update t1 set v2=2, version=version+1 where v1=1 and version=0; (Affected rows: 1)
04 - S2 執行 select * from t1; 看到1, 2, 1
05 - S1 執行 select * from t1; 看到1, 1, 0 - 無變化
06 - S1 執行 update t1 set v2=2, version=version+1 where v1=1 and version=0; 被掛起, 一直等待
07 - S2 執行 commit;  第06步的S1查詢結束, 顯示(Affected rows: 0)
08 - S1 執行 select * from t1; 依然看到1, 1, 0
09 - S1 執行 commit; 
10 - S1 執行 select * from t1; 看到1, 2, 1 - 這時候資料才更新

由此可以驗證, 在 REPEATABLE-READ 的隔離等級下, 一個事務並不能覺察到事務外部的資料變化, 所有讀取的資料自事務開始後就不變, 但是update類型的操作, 會受到事務外部資料變化的影響, 首先是如果同一行資料有外部事務未提交, 則當前操作需要排隊, 其次是如果同一行資料已經被外界更改, 則update操作會受影響, 例如本例中 Affected rows: 0

由此可見, 通過形如 update t1 set v2=2, version=version+1 where v1=1 and version=0 的方式來做並發控制是可行的.

 

MySQL 的開放式並行存取控制Optimistic concurrency control

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.