Junior — Middle
What types of mutual exclusions (Mutex) are implemented in the standard Go library?
sobes.tech AI
Answer from AI
The standard library of Go implements a primary mutual exclusion type — sync.Mutex. It is a simple mutex that provides locking and unlocking to protect critical sections of code from concurrent access.
Additionally, there is sync.RWMutex — an extended version of the mutex that allows multiple readers to hold the lock simultaneously, but writing is blocked exclusively.
Example of using sync.Mutex:
var mu sync.Mutex
var counter int
func increment() {
mu.Lock()
defer mu.Unlock()
counter++
}
And an example with sync.RWMutex:
var rwMu sync.RWMutex
var data int
func readData() int {
rwMu.RLock()
defer rwMu.RUnlock()
return data
}
func writeData(val int) {
rwMu.Lock()
defer rwMu.Unlock()
data = val
}