Middle
How does sync.RWMutex work and when should it be used?
sobes.tech AI
Answer from AI
sync.RWMutex in Go is a type of mutex that allows multiple goroutines to read data simultaneously (RLock), but blocks writing (Lock) until all readers have released the lock.
When to use:
- If you have data that is read frequently and rarely modified.
- To improve performance by allowing parallel reads but excluding concurrent writes.
Example:
var mu sync.RWMutex
var data int
func readData() int {
mu.RLock()
defer mu.RUnlock()
return data
}
func writeData(val int) {
mu.Lock()
defer mu.Unlock()
data = val
}
Thus, multiple calls to readData can execute simultaneously, but writeData will wait until all reads are finished and will block new reads until the write is complete.