go runtime_error ai_generated true

致命错误:所有goroutine都处于休眠状态 - 死锁!(goroutine泄漏)

fatal error: all goroutines are asleep - deadlock! (goroutine leak)

ID: go/goroutine-leak-channel-buffer

其他格式: JSON · Markdown 中文 · English
80%修复率
86%置信度
0证据数
2024-04-05首次发现

版本兼容性

版本状态引入弃用备注
1.18 active
1.19 active
1.20 active

根因分析

由于通道发送没有接收者且通道无缓冲,goroutine永远阻塞。

English

Goroutines are blocked forever because a channel send has no receiver and the channel is unbuffered.

generic

解决方案

  1. 95% 成功率 Ensure every send has a corresponding receive
    // Before: ch <- 1 (no reader)
    // After: 
    result := make(chan int)
    go func() { result <- doWork() }()
    val := <-result
  2. 90% 成功率 Use a context with cancellation to clean up goroutines
    ctx, cancel := context.WithCancel(context.Background())
    go func() {
        select {
        case ch <- val:
        case <-ctx.Done():
            return
        }
    }()
    cancel() // cleanup

无效尝试

常见但无效的做法:

  1. Increasing buffer size arbitrarily 70% 失败

    Only delays the leak; doesn't match send/receive pattern.

  2. Using time.After to timeout 60% 失败

    Goroutine still exists but leaks after timeout; not a clean solution.