Senior
What is the difference between Mutex and RWMutex?
sobes.tech AI
Answer from AI
Mutex (mutual exclusion) is a simple locking mechanism that allows only one goroutine to access the critical section of code at a time.
RWMutex (Read-Write Mutex) extends this idea by allowing multiple goroutines to read data simultaneously (permitting parallel read operations), but blocking access during writing. That is:
- Multiple readers can hold the lock simultaneously.
- Writing is only possible when there are no readers or other writers.
Example of using RWMutex:
var mu sync.RWMutex
var data int
func readData() int {
mu.RLock() // lock for reading
defer mu.RUnlock()
return data
}
func writeData(val int) {
mu.Lock() // lock for writing
defer mu.Unlock()
data = val
}
Thus, RWMutex improves performance in scenarios with frequent read operations and infrequent writes.