You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Timer是否会造成Goroutine泄漏?如何正确处理该场景?

问题解答

1. 停止Timer后,goroutine会永久阻塞吗?

会。当timer2.Stop()返回true时,说明定时器还未触发,此时定时器的C通道不会有任何值发送,也不会被自动关闭。goroutine里的<-timer2.C会一直处于等待接收数据的状态,最终导致这个goroutine永久阻塞,造成goroutine泄漏。

2. 正确处理方式

核心思路是给goroutine提供一个退出信号,避免它一直卡在接收timer通道的操作上。常见的实现方式是用select同时监听定时器通道和一个退出通道:

timer2 := time.NewTimer(time.Second)
quit := make(chan struct{})

go func() {
    select {
    case <-timer2.C:
        fmt.Println("Timer 2 fired")
    case <-quit:
        // 收到退出信号,直接退出goroutine
    }
}()

stop2 := timer2.Stop()
if stop2 {
    fmt.Println("Timer 2 stopped")
    close(quit) // 关闭退出通道,通知goroutine结束
}

注意:不要手动关闭Timer的C通道,因为Timer内部的逻辑可能还在引用这个通道,手动关闭可能引发其他未知问题。

内容的提问来源于stack exchange,提问作者pmoubed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 03:54:57