Junior — Middle
Can you explain what mutual thread blocking in a system means and how it occurs?
sobes.tech AI
Answer from AI
Deadlock is a situation in a multithreaded system where two or more threads permanently block each other, waiting for resources held by the other.
For example, thread A has acquired resource 1 and is waiting for resource 2, while thread B has acquired resource 2 and is waiting for resource 1. Neither thread can continue working because each is waiting for the resource held by the other.
In Go, this can happen when using mutexes or channels if the order of resource acquisition is not carefully planned. To avoid deadlocks, you should:
- Avoid cyclic dependencies when acquiring resources.
- Use timeouts or try-lock mechanisms with checks.
- Follow a consistent order when acquiring mutexes.
Example in Go with mutexes:
var mu1, mu2 sync.Mutex
func f1() {
mu1.Lock()
defer mu1.Unlock()
time.Sleep(time.Millisecond * 100) // simulate work
mu2.Lock() // can lead to deadlock if another thread has locked mu2 and is waiting for mu1
defer mu2.Unlock()
}
func f2() {
mu2.Lock()
defer mu2.Unlock()
time.Sleep(time.Millisecond * 100)
mu1.Lock()
defer mu1.Unlock()
}
If f1 and f2 are run simultaneously, deadlock may occur.