Junior — Middle
Milline on erinevus tavalise mutexi ja lugemis- ja kirjutamisvõimalusega mutexi (RWMutex) kasutamise vahel?
sobes.tech AI
Vastus AI-lt
The standard Mutex (sync.Mutex) in Go provides exclusive access to a resource: at any given moment, only one goroutine can hold the mutex, others wait.
The 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 improves 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()
If a normal Mutex is used, even reads will block each other, reducing parallelism.