What is the difference between RW Mutex and a regular mutex?
sobes.tech AI
Answer from AI
sync.RWMutex allows multiple goroutines to read data simultaneously, but only one goroutine to write data at a time. sync.Mutex blocks access for any other goroutine attempting to acquire the lock (whether for reading or writing) until the first goroutine releases the lock.
-
sync.Mutex: Exclusive lock. Either locked or unlocked. Only one goroutine can hold the mutex at any given time. Suitable when read and write operations are frequent or have similar durations.// Example of using Mutex var mu sync.Mutex var counter int func increment() { mu.Lock() counter++ mu.Unlock() } -
sync.RWMutex: Lock for reading and writing. Allows multiple goroutines to hold a read lock simultaneously, but the write lock is exclusive. A goroutine holding the write lock blocks both other write and read operations. Goroutines holding the read lock block write operations but not other read operations. Suitable when read operations occur much more frequently than write operations.// Example of using RWMutex var rwmu sync.RWMutex var data map[string]string = make(map[string]string) func readData(key string) string { rwmu.RLock() // Acquire read lock value := data[key] rwmu.RUnlock() // Release read lock return value } func writeData(key, value string) { rwmu.Lock() // Acquire write lock data[key] = value rwmu.Unlock() // Release write lock }
The main differences can be summarized in the table:
| Characteristic | sync.Mutex |
sync.RWMutex |
|---|---|---|
| Lock type | Exclusive (read/write) | Shared (read) + exclusive (write) |
| Concurrent access | One goroutine | Multiple goroutines for read, one for write |
| Lock method for read | Lock() |
RLock() |
| Lock method for write | Lock() |
Lock() |
| Unlock method for read | Unlock() |
RUnlock() |
| Unlock method for write | Unlock() |
Unlock() |
| Performance | Simpler, potentially slower with frequent reads | More complex, potentially faster with frequent reads and infrequent writes |