Middle+
How does RWMutex differ from Mutex and when is it more advantageous to use RWMutex?
sobes.tech AI
Answer from AI
Mutex is a basic mutex that provides exclusive access to a resource: at any given moment, only one goroutine can acquire the mutex and work with the protected data.
RWMutex (Read-Write Mutex) allows dividing locks into read and write. Multiple goroutines can acquire RLock (read) simultaneously if there is no active write. Write (Lock) is exclusive and blocks all other operations.
When is it beneficial to use RWMutex:
- If you have many read operations and few write operations,
RWMutexincreases parallelism by allowing multiple readers to work simultaneously. - If there are many write operations or read and write operations are roughly equal,
Mutexmight be simpler and more efficient.
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
}
Here, multiple goroutines can read data simultaneously, but writing is exclusive.