Junior — Middle
Selgitage, mis on Read-Write lukustus (RWMutex) ja kuidas seda kasutatakse andmetele juurdepääsu haldamiseks.
sobes.tech AI
Vastus AI-lt
The read-write lock (RWMutex) in Go is a synchronization mechanism that allows multiple goroutines to read data simultaneously while ensuring exclusive access during writing.
- RLock() / RUnlock() — lock for reading. Multiple goroutines can hold this lock at the same time.
- Lock() / Unlock() — lock for writing. Only one goroutine can hold it, and no reads are allowed during this time.
This increases performance when there are many read operations and few write operations.
Usage example:
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() concurrently, but if writeData() is called, it blocks all reads and writes until it completes.