5

In Go, does a call to time.Sleep() yield to other goroutines? I have a feeling it does, but in other answers (eg: Understanding goroutines) time.Sleep is not explicitly listed as a scheduling point.

Community
  • 1
  • 1
bk0
  • 1,300
  • 10
  • 12
  • 3
    Yes. Though sleep is special in a sense, all function calls are yield points. – JimB Jan 08 '16 at 01:03
  • While I know syscalls yield, do you have a reference for "all function calls are yield points"? I haven't been able to find substantiation for it. – bk0 Jan 08 '16 at 01:34

1 Answers1

6

Yes. See Pre-emption in the scheduler.

In prior releases, a goroutine that was looping forever could starve out other goroutines on the same thread, a serious problem when GOMAXPROCS provided only one user thread. In Go 1.2, this is partially addressed: The scheduler is invoked occasionally upon entry to a function. This means that any loop that includes a (non-inlined) function call can be pre-empted, allowing other goroutines to run on the same thread.

Following design docs are also good reads to learn more about scheduler:

ferhatelmas
  • 3,818
  • 1
  • 21
  • 25
  • "... any loop that includes a (non-inlined) function call can be pre-empted..." Since the Go compiler decides when to do inlining, how will I know whether the function I choose to call as a yield point in my loop will be inlined or not? For example, the `Time.IsZero()` function seems like a prime candidate for inlining, so it seems like the only way to use it reliably as a yield point would be to wrap it in a function that I write and mark with a `//go:noinline` pragma. This seems cumbersome enough that I think I must be misunderstanding something. What am I missing? – Hephaestus Aug 27 '21 at 01:13