sync.RWMutex
sync.RWMutex is a reader-writer lock. Many goroutines may hold RLock at once. Lock is exclusive. Use it when reads are common and writes are rare.
Detailed Explanation
A cache that is read on every request and rewritten once a minute is the textbook case. RLock around the read, Lock around the write. Readers do not wait for each other. A writer waits until all readers unlock, and new readers wait behind the writer (the exact fairness has improved over Go versions to avoid writer starvation).
The API is two pairs. RLock/RUnlock for shared access. Lock/Unlock for exclusive access. Mixing them up — RUnlock after Lock — panics. Document which fields the lock protects, same as a mutex.
Recursion still deadlocks. A goroutine that RLocks and then Locks the same RWMutex deadlocks. A goroutine that RLocks twice is allowed (multiple read locks from one goroutine), but then it must RUnlock the same number of times. Prefer one RLock per call.
Do not upgrade. There is no "I hold RLock, now I want Lock." Unlock the read lock, then take the write lock — and accept that the data may have changed in between. If upgrade is common, you wanted a plain Mutex.
When a Mutex is better. Short critical sections, or a write rate that is not rare. An RWMutex is more bookkeeping. If the "read" copies a pointer and returns, the critical section is tiny and a mutex is clearer.
What it costs. Uncontended read locks are cheap. Writer latency grows with the number of overlapping readers. If you need a consistent snapshot of a large map, consider swapping a whole map pointer under a mutex instead of holding RLock while ranging.
Code Examples
package main
import "sync"
type cache struct {
mu sync.RWMutex
m map[string]int
}
func (c *cache) Get(k string) (int, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
v, ok := c.m[k]
return v, ok
}
func (c *cache) Set(k string, v int) {
c.mu.Lock()
defer c.mu.Unlock()
if c.m == nil {
c.m = make(map[string]int)
}
c.m[k] = v
}
func main() {
var c cache
c.Set("n", 1)
_, _ = c.Get("n")
}Common Gotchas
Holding `RLock` during a slow operation blocks writers for that whole time
copy what you need and unlock.
A zero `RWMutex` is ready
do not copy after first use.
`RUnlock` without `RLock` (or mismatched pairs) panics
`RUnlock` without `RLock` (or mismatched pairs) panics
Taking `Lock` while holding `RLock` in the same goroutine deadlocks
Taking `Lock` while holding `RLock` in the same goroutine deadlocks