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.
The Readers-Writers problem: multiple readers can read simultaneously (reads don't conflict), but a writer needs exclusive access (a writer conflicts with both readers and other writers). Solution with RWMutex: readers acquire a read-lock (shared), writers acquire a 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): prioritizes readers; writers can starve if new readers keep arriving
- Writer-priority (Second Readers-Writers): prioritizes writers; readers can starve
- Fair (Third Readers-Writers): queue-based, FIFO — no starvation
Go's sync.RWMutex implements writer-priority: when a writer is waiting, new readers are blocked to prevent writer starvation. Java's ReentrantReadWriteLock allows configuring a fairness policy. When to use RWMutex: read-heavy workloads with infrequent writes (config caches, in-memory indexes). RWMutex has higher overhead than a regular Mutex — if the write/read ratio is high, a regular Mutex may be faster.