Junior — Middle
Have you experienced deadlock when working with multithreading?
sobes.tech AI
Answer from AI
Yes, I have experience with deadlock in multithreaded programs. Deadlock occurs when two or more threads wait forever for resources held by each other, leading to a halt in execution.
For example, if 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, a deadlock occurs.
In Go, this can happen when using mutexes or channels without proper synchronization. To avoid deadlock, it is important to:
- Always acquire resources in the same order.
- Use timeouts or contexts with cancellation.
- Minimize the time locks are held.
An example of a potential deadlock with mutexes:
var mu1, mu2 sync.Mutex
func f1() {
mu1.Lock()
defer mu1.Unlock()
time.Sleep(time.Second)
mu2.Lock()
defer mu2.Unlock()
// work
}
func f2() {
mu2.Lock()
defer mu2.Unlock()
time.Sleep(time.Second)
mu1.Lock()
defer mu1.Unlock()
// work
}
Here, f1 and f2 can deadlock if called simultaneously.