go resource_error ai_generated true

goroutine 泄漏:runtime.NumGoroutine() 无限增长;pprof 显示 goroutine 阻塞在 chan send

goroutine leak: runtime.NumGoroutine() grows unbounded; pprof shows goroutines blocked in chan send

ID: go/goroutine-leak-runtime-numgoroutine-grows-unbounded-ppro

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

版本兼容性

版本状态引入弃用备注
1.19 active — — —
1.21 active — — —
1.23 active — — —

根因分析

生产者 goroutine 因消费者提前返回(错误/超时)而永久阻塞在无缓冲 channel 的发送上,且无人再消费该 channel。

English

Producer goroutines block forever on an unbuffered channel because the consumer returned early (error/timeout) and nobody drains the channel.

generic

解决方案

  1. 95% 成功率
    go func() {
        defer close(out)
        for _, x := range items {
            select {
            case out <- x:
            case <-ctx.Done():
                return
            }
        }
    }()
  2. 88% 成功率
    defer func() {
        for range out {}
    }()

无效尝试

常见但无效的做法:

  1. 80% 失败

    Delays the leak; once the buffer fills under sustained load the goroutines block again.

  2. 95% 失败

    GC does not collect blocked goroutines; they remain referenced by the scheduler.