[並行控制] Concurrency control 指南 – 樂觀鎖|悲觀鎖

Intro

Concurrency control - 並行控制

分類上目前可分為三種:

  • 樂觀鎖(Optimistic Locking)

  • 悲觀鎖(Pessimistic Locking)

  • 半樂觀鎖 (Semi-optimistic Locking)

    • *

Database - 資料庫管理系統

樂觀鎖 - OCC

樂觀並行控制 - Optimistic Concurrency Control,縮寫「OCC」

  • 不利用內建鎖機制,而是利用應用層邏輯解決衝突
  • 可透過讀取資料時分派一個版本或時間戳,通過校驗後寫入否則中斷(實作上可利用寫入連帶驗證版本達成)
  • 適合交易之間資料競爭(data race)概率較小的應用情境

MySQL 實現範例

update DB.table set quantity = quantity -1 , version = version + 1 where id = 1 and version = 0;

悲觀鎖 - PCC

悲觀並行控制 - Pessimistic Concurrency Control,縮寫「PCC」

  • 利用內建鎖機制來解決衝突
  • 呈上,效率不佳且有增加產生死鎖(deadlock)機會
  • 鎖的分類上可以簡單分為兩大類:讀鎖 (Read Lock) 和不可讀鎖 (Write Lock)

MySQL 實現案例 (InnoDB Transaction)

# Row-level Lock for share (Read Lock)
SELECT * FROM parent WHERE NAME = 'Jones' FOR SHARE;

# Row-level Lock for update (Write Lock)
SELECT counter_field FROM child_codes FOR UPDATE;
UPDATE child_codes SET counter_field = counter_field + 1;

MySQL - InnoDB Locking Postgresql Explicit Locking - Row-Level Locks


OS - 作業系統

IPC (Inter-Process Communication) - 行程間通訊

(TBC)

Leave a Reply

Your email address will not be published. Required fields are marked *