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 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办