Junior — Middle
How is mutual exclusion (Mutex) implemented in programming systems?
sobes.tech AI
Answer from AI
In Go, the sync.Mutex type from the standard library is used to implement mutual exclusion (Mutex). A mutex provides exclusive access to shared resources, preventing multiple goroutines from executing the critical section simultaneously.
Example usage:
import (
"fmt"
"sync"
)
func main() {
var mu sync.Mutex
counter := 0
mu.Lock() // Acquire the mutex
counter++ // Critical section
mu.Unlock() // Release the mutex
fmt.Println(counter)
}
The mutex blocks other goroutines from executing code that tries to lock it until it is unlocked. This prevents race conditions when accessing shared data.