duanpang5583 2017-03-03 03:32
浏览 38
已采纳

了解Go中的比赛条件

I have the following very simple code:

for i := 0; i < 100; i++ {
    tt := time.AfterFunc(10*time.Microsecond, func() { log.Fatal("bleh!") })
    time.Sleep(2 * time.Microsecond)
    tt.Stop()
}

Now, it should seem that it would do nothing, and when I run it on the Go playground, it just quietly exits as expected, but when I run this on my Macbook, I invariably get errors, like:

go run example.go
2017/03/02 22:21:50 bleh!
2017/03/02 22:21:50 bleh!
exit status 1

And I can put that time on the AfterFunc quite high indeed, even as high as 50 or 100 μs and I'll still get the occasional "bleh!" and death. What are the guarantees around time.Sleep in Go? And what is a better way of testing that something ran within a specific amount of time?

  • 写回答

2条回答 默认 最新

  • dongwo7858 2017-03-03 03:48
    关注

    The guarantee is that time.Sleep(2 * time.Microsecond) will sleep for at least 2 microseconds, and time.AfterFunc(10 * time.Microsecond, ...) will call its callback after at least 10 microseconds. No upper limit is guaranteed (the underlying operating system could do anything it wants), and no relative ordering is guaranteed — if the sleep happens to take more than 10 microseconds, then the AfterFunc could end up before or after it.

    If you used reasonably long periods of time then it's very likely that you would observe things happening in the right order, because the Sleeping goroutine would get scheduled before the timer expired. But a microsecond is a very short period of time, and so, unscientifically speaking, deadlines that happen within microseconds of each other are very likely to happen in whatever order they feel like.

    The playground uses a modified runtime that fakes time, which incidentally is the best approach for testing as well. Modifying the runtime isn't really practical for most, but you might try the clockwork package which provides an interface to both real and fake clock objects. Otherwise, follow the same approach yourself — if you want something to be testable, it can't depend on time, because time is global and irreproducible. Instead, it has to get its notifications from some component that uses time in production, but is replaceable for testing.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)