CodeBlanks Logo Icon CodeBlanks

runtime.Gosched

Learn to voluntarily yield a goroutine with Gosched.

runtime.Gosched

runtime.Gosched() yields the current goroutine and puts it back on the queue; the P runs another goroutine, and then its turn comes again. The goroutine doesn't block, it just yields.

runtime.GOMAXPROCS(1)
go fmt.Println("goroutine")
runtime.Gosched()      // give the other one a chance
fmt.Println("main")

Since preemption arrived in Go 1.14 it's rarely needed in real code; you see it in tests and tight-loop experiments.

Don't use it for synchronization

The assumption "I called Gosched, so the goroutine must have run" is wrong; the scheduler doesn't guarantee it, and behavior changes on multi-core machines. To know that work has finished use real synchronization tools such as channels, sync.WaitGroup or sync.Once.

Practice Wait for the flag

Declare var hazir atomic.Bool. A goroutine sets the flag to true. main calls runtime.Gosched() in a loop until the flag is true, then prints "hazır".

Starter code

main.go
package main

import (
    "fmt"
    "runtime"
    "sync/atomic"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "runtime"
    "sync/atomic"
)

func main() {
    var hazir atomic.Bool
    go hazir.Store(true)
    for !hazir.Load() {
        runtime.Gosched()
    }
    fmt.Println("hazır")
}

Expected output

hazır

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the key difference between Gosched and time.Sleep(0)?

  • They are identical
  • Sleep(0) panics
  • Gosched ends the program
  • Gosched returns to the queue right away; Sleep goes through the timer Correct answer

Explanation: Gosched only yields; it is not a synchronization tool. For ordering guarantees use channels or a WaitGroup.

2 Yield

Question
for !hazir.Load() {
    runtime.____()
}
Answer
for !hazir.Load() {
    runtime.Gosched()
}

Explanation: Gosched lets other goroutines use the P while the loop waits.

3 Tool and guarantee

Term Meaning
Gosched Only yields
Channel Ordering guarantee
WaitGroup Waits for completion
atomic.Bool Safe flag

All lessons in Expert