go runtime_error ai_generated true

恐慌:运行时错误:向已关闭的通道发送数据(ticker.C)

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

ID: go/goroutine-ticker-stop-leak

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

版本兼容性

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

根因分析

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

English

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

generic

解决方案

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

无效尝试

常见但无效的做法:

  1. Ignoring ticker stop 90% 失败

    Causes goroutine leak and potential panic.

  2. Using recover() to catch panic 85% 失败

    Does not prevent data race on ticker.C.