liveBook · Manning

Deadlock

As explained in 100 Go Mistakes and How to Avoid Them

A deadlock is a state in which concurrent executions are permanently blocked because each is waiting for an event or resource that cannot become available.

A deadlock occurs when concurrent executions remain blocked because each waits for an event or resource that cannot become available. In Go, mutex scope, channel buffering, and indirect function calls can create this condition. section 9.0 section 9.8.2

A formatter re-enters a locked mutex

The mistake is locking Customer before validating age, then formatting the receiver in the error. fmt.Errorf invokes String, but String tries to acquire the same mutex through RLock while UpdateAge still holds its write lock. Execution blocks; if every goroutine is asleep, Go reports `fatal error: all goroutines are asleep - deadlock!`.

Use the fix that matches the source of the lock dependency:

  • Treat buffered channels cautiously: they allow sends to continue while capacity remains and can hide deadlocks that unbuffered channels expose immediately. section 9.7

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Traces a mutex deadlock through formatting and compares lock-scope and direct-formatting fixes, while treating channel deadlocks more briefly.
Examples
Uses a Customer.UpdateAge and String interaction, a runtime deadlock panic, and buffered-versus-unbuffered channel behavior.
What it assumes
Assumes familiarity with Go concurrency primitives, mutexes, channels, goroutines, and method calls.
What you can do after
Diagnose deadlocks by tracing lock ownership and indirect calls, then reduce lock scope or remove mutex acquisition from formatting.
How it connects
Connects deadlocks with goroutines, channels, mutexes, string formatting, synchronization, and unit testing.

Also explained in

Compare how 15 books explain deadlock →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.