Junior — Middle
How can mutual blocking be prevented when using two mutexes?
sobes.tech AI
Answer from AI
To prevent deadlock when using two mutexes in Go, you should follow a consistent order of acquiring mutexes in all goroutines. That is, always lock mutexes in the same order. For example, if you have mutexes mu1 and mu2, always lock mu1 first, then mu2. This will prevent a situation where one goroutine waits for mu2 while another waits for mu1, causing both to block.
Example:
var mu1, mu2 sync.Mutex
func f() {
mu1.Lock()
defer mu1.Unlock()
mu2.Lock()
defer mu2.Unlock()
// critical section
}
func g() {
mu1.Lock() // always lock mu1 first
defer mu1.Unlock()
mu2.Lock()
defer mu2.Unlock()
// critical section
}
If the order of locking mutexes varies, deadlock can occur. You can also use timeouts or try-lock mechanisms, but in Go, the standard sync.Mutex does not support try-lock, so the main point is to maintain a consistent locking order.