Middle+
What is Deadlock? How to avoid deadlock?
sobes.tech AI
Answer from AI
Deadlock (mutual blocking) is a situation in multithreaded or concurrent systems where two or more processes (or goroutines in Go) are permanently blocking each other, waiting for resources held by each other. As a result, none of the processes can continue.
To avoid deadlock, the following approaches can be used:
- Avoid cyclic dependencies: always acquire resources in the same order.
- Use timeouts when acquiring locks: if a resource is unavailable, release already acquired resources and retry.
- Minimize the time locks are held: keep locks only on critical sections of code.
- Use channels and other high-level primitives in Go that help avoid explicit locking.
Example of a potential deadlock in Go:
g1 := make(chan struct{})
g2 := make(chan struct{})
// Goroutine 1
go func() {
<-g1
g2 <- struct{}{}
}()
// Goroutine 2
go func() {
<-g2
g1 <- struct{}{}
}()
// Neither goroutine can continue because they are waiting for each other
To prevent this, you need to think through the logic or use select with a timeout.