Junior — Middle
Mis on RWMutex sünkroniseerimise tüübi eesmärk programmeerimiskeeles?
sobes.tech AI
Vastus AI-lt
In the Go language, the RWMutex (Read-Write Mutex) type is used for synchronizing access to shared resources. It allows multiple goroutines to read data simultaneously but blocks writing while reading is in progress, and vice versa.
The main purpose of RWMutex is to improve performance in scenarios where read operations are significantly more frequent than write operations. It provides two types of locks:
RLock()— read lock, allows multiple readers to access simultaneously.Lock()— write lock, exclusive access.
Example of usage:
var mu sync.RWMutex
var data int
func readData() int {
mu.RLock()
defer mu.RUnlock()
return data
}
func writeData(val int) {
mu.Lock()
defer mu.Unlock()
data = val
}
Thus, RWMutex helps efficiently manage concurrent access and minimizes locking during frequent reads.