Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does golang time.Sleep do when I suspend the computer?

Tags:

go

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.

like image 633
Karel Bílek Avatar asked Dec 09 '25 16:12

Karel Bílek


1 Answers

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())
}
  • T0: time.Sleep(time.Hour)
  • T0 + 30 minutes: suspend OS for 15 minutes
  • T0 + 45 minutes: wake up OS
  • T0 + 75 minutes: go routine returns

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.

like image 60
Neo Anderson Avatar answered Dec 11 '25 11:12

Neo Anderson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!