Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang time.Sleep bug?

Tags:

time

go

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.

like image 513
user2139281 Avatar asked Jul 31 '15 08:07

user2139281


2 Answers

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.

like image 154
chill Avatar answered Nov 09 '22 23:11

chill


time.Sleep(20_000_000_000) n is nanoseconds

like image 33
Vovan Avatar answered Nov 09 '22 22:11

Vovan