go runtime_error ai_generated true

panic: runtime error: send on closed channel (ticker.C)

ID: go/goroutine-ticker-stop-leak

Also available as: JSON · Markdown · 中文
80%Fix Rate
82%Confidence
0Evidence
2025-01-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active
1.19 active
1.20 active
1.21 active
1.22 active

Root Cause

Using a time.Ticker after it has been stopped, causing a send on a closed channel if the ticker fires.

generic

中文

在time.Ticker停止后使用它,如果计时器触发会导致向已关闭的通道发送数据。

Workarounds

  1. 90% success Stop ticker and drain channel before closing
    ticker.Stop(); ticker.C = nil // or use select with done channel
  2. 95% success Use time.NewTicker with a done channel
    done := make(chan struct{}); go func() { for { select { case <-ticker.C: // handle case <-done: return } } }()

Dead Ends

Common approaches that don't work:

  1. Ignoring ticker stop 90% fail

    Causes goroutine leak and potential panic.

  2. Using recover() to catch panic 85% fail

    Does not prevent data race on ticker.C.