Deadlock
A deadlock is a set of goroutines that will never proceed because each is waiting for another. The runtime detects when every goroutine is asleep and crashes with fatal error: all goroutines are asleep - deadlock!.
Detailed Explanation
The classic pair: goroutine A holds mutex 1 and wants mutex 2; goroutine B holds 2 and wants 1. Channel deadlocks are more common in Go. ch := make(chan int); ch <- 1 in main with no receiver parks the only runnable goroutine. Two goroutines each waiting to send to the other, with unbuffered channels and no extra buffer, is the same idea.
The runtime's detector is not complete. It fires when there is no runnable goroutine. If one goroutine is in time.Sleep or blocked on I/O, the process stays up while your workers sit forever. A leaked goroutine blocked on a channel is a deadlock of that worker, not a process-wide fatal.
Lock order. If you must take two mutexes, take them in a global order everywhere (say, by address or by name). Document the order. Prefer one mutex per graph of fields.
Channel protocols. Every send needs a receiver that will eventually run. Every Wait needs the matching Done. Every range ch needs a close. Draw the ownership: who sends, who closes, who waits.
select can prevent some deadlocks by waiting on cancel as well as the channel. A timeout is an escape hatch, not a design. Prefer a correct protocol.
What it costs. A process-wide deadlock is easy to see (the fatal). A partial deadlock is a stuck request and a goroutine dump you take with pprof or SIGQUIT. Design so that cancel unblocks waits.
Code Examples
package main
func deadlockChan() {
ch := make(chan int)
ch <- 1 // no receiver
}
func lockOrder() {
var a, b sync.Mutex
go func() {
a.Lock()
b.Lock()
b.Unlock()
a.Unlock()
}()
b.Lock()
a.Lock() // may deadlock with the goroutine
a.Unlock()
b.Unlock()
}func safeSend(ctx context.Context, ch chan<- int, v int) error {
select {
case ch <- v:
return nil
case <-ctx.Done():
return ctx.Err()
}
}Common Gotchas
Inconsistent lock order is a deadlock that `-race` will not report
race and deadlock are different bugs.
`select {}` is an intentional all-asleep if it is the last goroutine
the runtime still fatals. Keep a real wait (`WaitGroup`, `<-done`) instead.
Unbuffered send in the only live goroutine is a fatal deadlock
Unbuffered send in the only live goroutine is a fatal deadlock
The all-asleep fatal does not catch "one sleeper plus stuck workers."
The all-asleep fatal does not catch "one sleeper plus stuck workers."