go runtime_error ai_generated true

fatal error: all goroutines are asleep - deadlock!

ID: go/deadlock-unbuffered-channel-single-goroutine

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-03-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.21 active

Root Cause

Sending on an unbuffered channel without a receiver in the same goroutine blocks forever, causing a deadlock.

generic

中文

在没有接收方的同一 goroutine 中向无缓冲通道发送数据会永久阻塞,导致死锁。

Workarounds

  1. 95% success
    ch := make(chan int)
    go func() { ch <- 42 }()
    value := <-ch
    fmt.Println(value)
  2. 90% success
    ch := make(chan int, 1)
    ch <- 42
    fmt.Println(<-ch)

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Only works if the sender doesn't need to wait for a receiver; if the buffer fills, the same deadlock occurs.

  2. 90% fail

    Sleeping doesn't create a receiver; the goroutine still blocks indefinitely.

  3. 100% fail

    The program terminates immediately; no recovery is possible.