Senior
RWMutex — what is it? Why is it more efficient?
sobes.tech AI
Answer from AI
RWMutex (Read-Write Mutex) in Go is a type of mutex that allows multiple goroutines to read data simultaneously but guarantees exclusive access during writing. This is achieved by separating locks into "read" and "write".
Why it is more efficient:
- Allows many readers to access the resource concurrently without mutual blocking.
- Writing locks out all readers and other writers, ensuring data integrity.
- In scenarios with frequent reads and infrequent writes, RWMutex reduces contention and improves performance compared to a regular Mutex.
Example usage:
var mu sync.RWMutex
var data int
// Reading
mu.RLock()
value := data
mu.RUnlock()
// Writing
mu.Lock()
data = 42
mu.Unlock()
Thus, RWMutex is effective where reads significantly outnumber writes.