Explanation
What just happened
main sent on an unbuffered channel. A send there waits until another goroutine receives, and there was none. With every goroutine waiting and nothing left to wake one, the runtime stopped the program.
Try the what-if switch
- wait before reading: workers send results while main sits in
wg.Wait(). Each side waits for the other. - close after Wait, in a goroutine: main reads as the workers send; a helper waits, then closes. Prints
sum: 5. - in a server: no error: one goroutine waits on the network, so the same bug just hangs.
Why
An unbuffered channel hands a value directly from one goroutine to another, so both must be there. The runtime can only prove a deadlock when no goroutine could ever run again.
How to fix it
Make sure someone receives: read in another goroutine, or close the channel from a goroutine that waits for the senders.
Watch out
A real program rarely gets this message. Any goroutine waiting on a socket or a timer keeps it from firing, and the deadlock becomes a silent hang.
Common questions
What does fatal error: all goroutines are asleep - deadlock! mean?
Every goroutine in the program is blocked and none can wake another, so the Go runtime stops the program with exit code 2. The crash report shows where each one waits, like main in [chan send].
Why does calling wg.Wait() before reading the results deadlock?
Each worker's send on an unbuffered channel waits for a reader, and main, the reader, waits in wg.Wait() for the workers. Run wg.Wait() and close() in their own goroutine, and read in main.
Why doesn't my server crash with this error?
The check only fires when every goroutine is blocked. A goroutine waiting on the network, or just sleeping in a loop, could still wake, so Go reports nothing and the program hangs.
Verified: this timeline matches a real program, checked in CI on Go 1.26 and 1.27. How we verify. Unclear or wrong? Tell us