dongyanghan0556 2016-05-28 04:13
浏览 17
已采纳

我在哪里创建股票行情股票有关系吗?

Is there any difference between

ticker := time.NewTicker(1 * time.Second)

go func() {
    for _ = range ticker.C {
        fmt.Print("Tick")
    }
}()

time.Sleep(3)
ticker.Stop()

and

var ticker *time.Ticker

go func() {
    ticker = time.NewTicker(1 * time.Second)
    for _ = range ticker.C {
        fmt.Print("Tick")
    }
}()

time.Sleep(3)
ticker.Stop()

in terms of thread-safeness, especially when the work in the function takes longer than a tick's period?

I am asking because (when stopping the Ticker is not required) the latter can be shortened to

go func() {
    for ticker := time.NewTicker(1 * time.Second) ;; <-ticker.C {
        fmt.Print("Tick")
    }
}()

while the former cannot. This form has the additional advantage that the first tick is triggered right away.

  • 写回答

1条回答 默认 最新

  • douyi7055 2016-05-28 06:04
    关注

    The second version of the code is wrong: it has a race condition.

    var ticker *time.Ticker
    
    go func() {
        ticker = time.NewTicker(1 * time.Second)
        for _ = range ticker.C {
            fmt.Print("Tick")
        }
    }()
    
    time.Sleep(3)
    ticker.Stop()
    

    There's no synchronization between the assignment to ticker inside the goroutine and the use of ticker in the ticker.Stop() call.

    In practice this will almost always be harmless because of the long time.Sleep(3), but such races should be avoided if possible because even if they're harmless today they may cause trouble later. For example, if instead of Sleep you have some code that takes a variable amount of time, you may see nil pointer panics if that code happens to take a very short amount of time.

    So for that reason, I'd always use the first version of your code (the one that creates the ticker outside the goroutine).

    The third version of the code (where the ticker is used entirely inside the goroutine) is also good. I'd definitely use this shorter version of the code where the ticker is defined inside the goroutine if that's possible. The shortness of the code is nice, but I also like that the code outside doesn't see the ticker at all, so it's easy for the reader of the code to understand the scope of the ticker.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 打开软件提示错误:failed to get wglChoosePixelFormatARB
  • ¥30 电脑误删了手机的照片怎么恢复?
  • ¥15 (标签-python|关键词-char)
  • ¥15 python+selenium,在新增时弹出了一个输入框
  • ¥15 苹果验机结果的api接口哪里有??单次调用1毛钱及以下。
  • ¥20 学生成绩管理系统设计
  • ¥15 来一个cc穿盾脚本开发者
  • ¥15 CST2023安装报错
  • ¥15 使用diffusionbert生成文字 结果是PAD和UNK怎么办
  • ¥15 有人懂怎么做大模型的客服系统吗?卡住了卡住了