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 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c