dqq46733 2015-07-31 08:06
浏览 82
已采纳

golang时间。睡眠错误?

I make test code below(gotest.go)

package main

import (
    "fmt"
    "time"
    "sync"
)        

func main() {
    var wg sync.WaitGroup
    wg.Add(1)
    go testa()    

    wg.Wait()
}

func testa() {
    for {
        fmt.Println("test goroutine")
        time.Sleep(2 * time.Second)
    }
}

console

go run gotest.go

and, change my computer's date (ex : 2015-07-30 -> 2015-07-29)

and then, println not printed!!

is it bug??

(It is working to set next day)

I use MacOs latest ver. Thank you.

  • 写回答

1条回答 默认 最新

  • douliao7354 2015-07-31 08:35
    关注

    Internally sleep is done with absolute time: if you call Sleep(n) at time T the program is scheduled not to wake up after n time, but at time T + n.

    This is generally preferable because:

    • time usually does not flow backwards

    • due to OS scheduling delays a program which repeatedly sleeps may lag behind schedule indefinitely; using absolute time make it compensate for delays by sleeping for shorter intervals.

    In your case, you just have to wait for a day for the program to start printing again. :D

    Or set a time just a little in the past (say 15 sec), and see the program resuming after 15+2 sec.

    PS. To clarify what happens with an example:

    At 2016-08-25 16:27:12 the program calls time.Sleep(2 * time.Second) The Go runtime schedules the goroutine to be woken up on 2016-08-25 at 16:27:14 and puts the goroutine to sleep

    meanwhile ...

    the user sets the system time to 2016-08-24 16:27:13

    now the timeout is scheduled to expire one day and one second later.

    This should not happen on systems, on which Go uses POSIX CLOCK_MONOTONIC or equivalent thereof.

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

报告相同问题?

悬赏问题

  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊