Junior — Middle
How to ensure mutual exclusion when using two Mutex objects?
sobes.tech AI
Answer from AI
In Go, to ensure mutual exclusion when working with multiple Mutexes, it is important to avoid deadlocks, which can occur if two goroutines try to acquire two mutexes in different orders.
To ensure correct mutual exclusion when using two Mutexes, you should:
- Always acquire the mutexes in the same order in all goroutines.
- If possible, combine the data protected by the two mutexes under a single mutex.
An example of the correct order of acquiring two mutexes:
var mu1, mu2 sync.Mutex
func safeFunction() {
mu1.Lock()
defer mu1.Unlock()
mu2.Lock()
defer mu2.Unlock()
// Critical section protected by two mutexes
}
If another goroutine also acquires mu1 and then mu2, there will be no deadlock.
If the order of acquisition differs, a deadlock may occur. Therefore, the main rule is to follow a consistent order of acquiring mutexes.