Readers-Writers problem: nhiều reader có thể đọc đồng thời (read không conflict), nhưng writer cần exclusive access (writer conflict với cả reader và writer khác). Solution với RWMutex: reader acquire read-lock (shared), writer acquire write-lock (exclusive). Go:
var mu sync.RWMutex
// Reader:
mu.RLock()
defer mu.RUnlock()
// Writer:
mu.Lock()
defer mu.Unlock()Trade-offs:
- Reader-priority (First Readers-Writers): ưu tiên reader, writer có thể starvation nếu liên tục có reader mới
- Writer-priority (Second Readers-Writers): ưu tiên writer, reader có thể starvation
- Fair (Third Readers-Writers): queue-based, FIFO — không starvation
Go sync.RWMutex implement writer-priority: khi writer đang chờ, new readers bị block để tránh writer starvation. Java ReentrantReadWriteLock cho phép chọn fairness policy. Khi nào dùng RWMutex: read-heavy workloads với ít write (config cache, in-memory index). Overhead cao hơn regular Mutex — nếu write/read ratio cao, regular Mutex có thể nhanh hơn.