sync.RWMutex
Use `sync.RWMutex` only when read-heavy contention is real and measured; `sync.Mutex` stays the default.
Canonical guidance
- start with
sync.Mutex - switch to
sync.RWMutexonly for real read-heavy contention - keep lock ownership and protected invariants obvious
Use when
- read-mostly caches
- configuration snapshots with infrequent writes
- measured lock contention on many concurrent readers
Avoid
- choosing
RWMutexby reflex - holding
RLockacross long operations - trying to upgrade
RLockintoLock
Preferred pattern
- short
RLocksections for pure reads, shortLocksections for mutations
Anti-pattern
- replacing every mutex with
RWMutex“for scalability”
Explanation: This is tempting because read locks sound cheaper, but extra lock states add complexity and may not improve throughput.
Why
RWMutexis a specialization, not the baseline synchronization tool
Related pages
Sources
- sync package - Go Team
- The Go Memory Model - Go Team