Junior — Middle
What is the difference between using a standard mutex and a read-write mutex (RWMutex)?
sobes.tech AI
Answer from AI
The standard mutex (sync.Mutex) in Go provides exclusive access to a resource: at any given moment, only one goroutine can acquire the mutex, while others wait.
A read-write mutex (sync.RWMutex) allows:
- Multiple goroutines to acquire the mutex for reading (RLock) simultaneously if there is no writer.
- Only one goroutine can acquire the mutex for writing (Lock), blocking all readers and other writers.
This increases performance in scenarios where read operations are much more frequent than write operations, as reads do not block each other.
Example:
var mu sync.RWMutex
var data int
// Reading
mu.RLock()
fmt.Println(data)
mu.RUnlock()
// Writing
mu.Lock()
data = 42
mu.Unlock()
Using a regular Mutex would block even reads from each other, reducing parallelism.