go resource_error ai_generated true

致命错误:运行时:内存不足(定时器通道泄漏)

fatal error: runtime: out of memory (timer channel leak)

ID: go/goroutine-timer-channel-leak

其他格式: JSON · Markdown 中文 · English
80%修复率
84%置信度
0证据数
2025-01-15首次发现

版本兼容性

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

根因分析

创建大量 time.Timer 或 time.Ticker 而不停止它们,导致协程和通道泄漏,耗尽内存。

English

Creating many time.Timer or time.Ticker without stopping them, causing goroutine and channel leaks that exhaust memory.

generic

解决方案

  1. 95% 成功率 Always stop timers after use with defer.
    timer := time.NewTimer(1 * time.Second)
    defer timer.Stop()
    select {
    case <-timer.C:
        // do something
    }
  2. 90% 成功率 Use time.NewTicker and stop it when done.
    ticker := time.NewTicker(1 * time.Second)
    defer ticker.Stop()
    for range ticker.C {
        // periodic work
        if condition {
            break
        }
    }

无效尝试

常见但无效的做法:

  1. Using time.After in a loop without resetting. 90% 失败

    Each call to time.After creates a new timer; if not stopped, they accumulate.

  2. Assuming timers are garbage collected after firing. 80% 失败

    Timers are not GC'd until they fire or are stopped; if not stopped, they remain in memory.