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条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!