Junior — Middle
Explain what a Read-Write lock (RWMutex) is and how it is used to manage data access.
sobes.tech AI
Answer from AI
Read-Write lock (RWMutex) in Go is a synchronization mechanism that allows multiple goroutines to read data simultaneously but guarantees exclusive access during writing.
- RLock() / RUnlock() — lock for reading. Multiple goroutines can hold this lock simultaneously.
- Lock() / Unlock() — lock for writing. Only one goroutine can hold it, and no reads are allowed during this time.
This improves performance when there are many read operations and infrequent writes.
Example usage:
var rwMutex sync.RWMutex
var data int
func readData() int {
rwMutex.RLock()
defer rwMutex.RUnlock()
return data
}
func writeData(val int) {
rwMutex.Lock()
defer rwMutex.Unlock()
data = val
}
In this example, multiple goroutines can call readData() simultaneously, but if writeData() is called, it blocks all reads and writes until it finishes.