0

I looked into the source for time.Sleep. Found that there is just one line of declaration with no definition. I'm curious as to how it's actually working.

This is the only line is the source, which I couldn't wrap my head around.

func Sleep(d Duration)

So far I've looked into the source code, did some digging online. All links, explain how to use time.Sleep but not how it works, which is understandable.

  • 2
    Does [this](https://stackoverflow.com/a/32148983/11810946) answer your question? (question has a different focus but answer is spot on). – Brits Jun 13 '23 at 00:24
  • 1
    The implementation is [here](https://github.com/golang/go/blob/0b5a4afec9df67157891732e5ca660eaf1efab34/src/runtime/time.go#L175-L196). – Charlie Tumahai Jun 13 '23 at 00:27
  • Thank you both. How did you know where to look for this? Also, what is the mechanism that decides to run this definition. When `time.Sleep` is called? Is it just this `//go:linkname timeSleep time.Sleep`? Finally, why is it implemented this way? – Cijin Cherian Jun 13 '23 at 00:33

1 Answers1

-1

The source function is timeSleep

Source code

Basically they maintain the timers in a heap. And call gopark on the running goroutine to put it into sleep(lock).

Tawfik Nasser
  • 1,018
  • 9
  • 17