duanlao1552 2018-05-07 23:27
浏览 296
已采纳

如何正确停止计时器?

var timer *time.Timer

func A() {
    timer.Stop() // cancel old timer
    go B() // new timer
}

func B() {
    timer = time.NewTimer(100 * time.Millisecond)
    select {
    case <- timer.C:
    // do something for timeout, like change state
    }
}

Function A and B are all in different goroutines.

Say A is in a RPC goroutine. When application receives RPC request, it will cancel the old timer in B, and start a new timer in another goroutine.

The doc say:

Stop does not close the channel, to prevent a read from the channel succeeding incorrectly.

So how to break the select in B to avoid goroutine leak?

  • 写回答

2条回答 默认 最新

  • dongshi3361 2018-05-08 08:23
    关注

    Use an additional, independent cancellation signal. Since you already have a select statement in place, another channel is an obvious choice:

    import "time"
    
    var timer *time.Timer
    var canceled = make(chan struct{})
    
    func A() {
        // cancel all current Bs
        select {
        case canceled <- struct{}{}:
        default:
        }   
    
        timer.Stop()
    
        go B()       // new timer
    }
    
    func B() {
        timer = time.NewTimer(100 * time.Millisecond)
        select {
        case <-timer.C:
            // do something for timeout, like change state
        case <-canceled:
            // timer aborted
        }
    }
    

    Note that all As and Bs race against each other for the timer value. With the code above it is not necessary to have A stop the timer, so you don't need a global timer, eliminating the race:

    import "time"
    
    var canceled = make(chan struct{})
    
    func A() {
        // cancel all current Bs
        select {
        case canceled <- struct{}{}:
        default:
        }
    
        go B()
    }
    
    func B() {
        select {
        case <-time.After(100 * time.Millisecond):
            // do something for timeout, like change state
        case <-canceled:
            // aborted
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 MPLS/VPN实验中MPLS的配置问题
  • ¥15 materialstudio氢键计算问题
  • ¥15 已知隐函数其中一个变量的,求另外一个变量
  • ¥15 echarts图表制作
  • ¥15 halcon根据玻璃面板纹路取区域
  • ¥15 HFSS设计小型化180度耦合器
  • ¥15 使用CInternetSession,CHttpFile读取网页文件时有些电脑上会卡住怎么办?
  • ¥15 水下机器人的半物理仿真研究
  • ¥15 微服务假死,一段时间后自动恢复,如何排查处理
  • ¥50 webrtc-streamer TCP rtsp