When I have this simple code in golang
package main
import "time"
func main() {
time.Sleep(1 * time.Hour)
}
And in the middle of the one hour, I suspend the computer, how do the time "count"?
I am looking at the documentation and it's not completely clear to me.
time.Sleep() ends up invoking a low-level function that interacts with the operating system to suspend the execution of the current goroutine for the specified duration. This function is implemented in the runtime package.
I just tested on Windows:
To reproduce this simple test, run this snippet and suspend the OS while the go routine is still running:
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println(time.Now())
time.Sleep(time.Minute)
fmt.Println(time.Now())
}
This behaviour may be different on other operating systems, which probably explains the "for at least" found in the documentation of the time.Sleep() function:
// Sleep pauses the current goroutine for at least the duration d.
// A negative or zero duration causes Sleep to return immediately.
func Sleep(d Duration)
EDIT:
Some useful info here:
As of Go 1.23, the Go scheduler associates a high-resolution timer with the IOCP port using the Windows API NtAssociateWaitCompletionPacket. When the timer expires, the Windows kernel wakes up the sleeping thread –if it hasn’t already been woken up by new I/O work arriving. Then, the Go scheduler uses the thread to run the sleeping goroutine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With