dongmi4720 2017-04-25 16:32
浏览 85
已采纳

长度为0的Golang计时器

I've written a code snipped that creates a timer with a 0 length time, and it does not immediately expire (which is what I expected). A very short sleep call does make it expire, but I'm confused as to why.

The reason I care is that the code using this idea has a snippet that returns 0 on a low probability error, with the idea that the timer should be set to immediately expire, and retry a function. I do not believe that the nanosecond sleep needed here will affect my implementation, but it bothers me.

Did I make a mistake, is this expected behaviour?

Thanks!

 package main

    import (
        "fmt"
        "time"
    )

    func main() {
        testTimer := time.NewTimer(time.Duration(0) * time.Millisecond)
        fmt.Println(Expired(testTimer))
        time.Sleep(time.Nanosecond)
        fmt.Println(Expired(testTimer))
    }

    func Expired(T *time.Timer) bool {
        select {
        case <-T.C:
            return true
        default:
            return false
        }
    }

Playground link: https://play.golang.org/p/xLLHoR8aKq

Prints

false
true
  • 写回答

3条回答 默认 最新

  • dougan5772 2017-04-25 16:45
    关注

    time.NewTimer() does not guarantee maximum wait time. It only guarantees a minimum wait time. Quoting from its doc:

    NewTimer creates a new Timer that will send the current time on its channel after at least duration d.

    So passing a zero duration to time.NewTimer(), it's not a surprise the returned time.Timer is not "expired" immediately.

    The returned timer could be "expired" immediately if the implementation would check if the passed duration is zero, and would send a value on the timer's channel before returning it, but it does not. Instead it starts an internal timer normally as it does for any given duration, which will take care of sending a value on its channel, but only some time in the future.

    Note that with multiple CPU cores and with runtime.GOMAXPROCS() being greater than 1 there is a slight chance that another goroutine (internal to the time package) sends a value on the timer's channel before NewTimer() returns, but this is a very small chance... Also since this is implementation detail, a future version might add this "optimization" to check for 0 passed duration, and act as you expected it, but as with all implementation details, don't count on it. Count on what's documented, and expect no more.

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

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据