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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵