go resource_error ai_generated true

warning: goroutine leak detected (in goroutine 5)

ID: go/goroutine-leak-without-waitgroup

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2024-07-11First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.22 active

Root Cause

Goroutines that never exit due to blocked channel operations or infinite loops leak memory.

generic

中文

由于通道操作阻塞或无限循环而永不退出的 goroutine 会导致内存泄漏。

Workarounds

  1. 95% success
    var wg sync.WaitGroup
    wg.Add(1)
    go func() {
        defer wg.Done()
        // do work
    }()
    wg.Wait()
  2. 90% success
    ctx, cancel := context.WithCancel(context.Background())
    go func() {
        select {
        case <-ctx.Done():
            return
        case <-time.After(time.Second):
            // work
        }
    }()
    cancel()

Dead Ends

Common approaches that don't work:

  1. 100% fail

    GC doesn't collect goroutines; they are not garbage.

  2. 90% fail

    Temporary mitigation; eventually memory exhausts.

  3. 80% fail

    Leaks accumulate, causing OOM crashes.