[英]Why MySQL InnoDB can handle concurrent updates and PostgreSQL can't?
[英]MySQL InnoDB concurrent updates
您有一個具有以下兩列的InnoDB表A:id(PK),狀態
兩個線程按以下順序訪問表:
Thread 1: SELECT id from A where status = 0 LIMIT 1;
Thread 2: SELECT id from A where status = 0 LIMIT 1;
兩個線程都選擇ID 1。
Thread 1: UPDATE A SET status = 1 WHERE id = 1 AND status = 0;
Thread 2: UPDATE A SET status = 2 WHERE id = 1 AND status = 0;
兩個線程是否有可能更新同一行?
現在添加交易:
Thread 1: SELECT id from A where status = 0 LIMIT 1;
Thread 2: SELECT id from A where status = 0 LIMIT 1;
Thread 1: START TRANSACTION;
Thread 2: START TRANSACTION;
Thread 1: UPDATE A SET status = 1 WHERE id = 1 AND status = 0;
Thread 2: UPDATE A SET status = 2 WHERE id = 1 AND status = 0;
Thread 1: COMMIT;
Thread 2: COMMIT;
現在是否有可能兩個線程都將更新該行?
無論哪種情況,如果都可以更新兩行,那么解決該問題的正確方法是什么?
默認情況下,InnoDB上的鎖定機制是REPEATABLE_READ (請參閱https://dev.mysql.com/doc/refman/5.7/en/innodb-transaction-isolation-levels.html#isolevel_repeatable-read )。 這意味着如果對同一索引執行兩次更新將自動進行,但是我不相信您可以保證先進行哪個更新,而無需在程序中添加一些邏輯。 (第一次更新將由線程首先獲取鎖來完成)。
因此,要管理以正確的順序完成更新,您將需要在程序內部實現邏輯(如果是Java,我將看看Barrier , Latches和Semaphores )。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.