go
runtime_error
ai_generated
true
致命错误:所有协程都在休眠 - 死锁!(无缓冲通道发送)
fatal error: all goroutines are asleep - deadlock! (unbuffered channel send)
ID: go/goroutine-unbuffered-channel-blocking
80%修复率
87%置信度
0证据数
2024-09-18首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.20 | active | — | — | — |
| 1.21 | active | — | — | — |
根因分析
无缓冲通道发送会阻塞直到有接收者就绪;如果没有接收者,协程会死锁。
English
An unbuffered channel send blocks until a receiver is ready; if no receiver exists, the goroutine deadlocks.
解决方案
-
95% 成功率 Use a buffered channel to allow sends without immediate receiver.
ch := make(chan int, 1) ch <- 42 // non-blocking val := <-ch fmt.Println(val)
-
100% 成功率 Ensure a receiver goroutine is started before sending.
ch := make(chan int) go func() { val := <-ch fmt.Println(val) }() ch <- 42 // now receiver is ready
无效尝试
常见但无效的做法:
-
Using a buffered channel but with size 0, which is unbuffered.
90% 失败
make(chan int, 0) creates an unbuffered channel, still blocking.
-
Adding a receiver in the same goroutine after the send.
100% 失败
The send blocks before the receiver is reached, causing deadlock.