CodeBlanks Logo Icon CodeBlanks

Summary - Scheduler

Combine scheduler mechanisms to write an analysis.

Scheduler summary

Gs wait in Ps' local queues and run on Ms. An idle P steals work; the global queue is checked regularly; long runners are stopped by a signal; on a blocking syscall the P is handed off to another M; network I/O waits in the netpoller.

GODEBUG=schedtrace=1000 ./app   // scheduler summary every second

The schedtrace output shows P, M and G counts and queue lengths.

GOMAXPROCS in containers

If a container is limited to 2 CPUs but the machine has 64 cores, before Go 1.25 GOMAXPROCS becomes 64 and the program gets throttled by the CPU quota. Go 1.25 reads cgroup limits and sets it automatically; on older versions the go.uber.org/automaxprocs package does the same.

Practice Setting GOMAXPROCS

Set the P count to 2 with eski := runtime.GOMAXPROCS(2), read and print the new value with runtime.GOMAXPROCS(0), then restore it with runtime.GOMAXPROCS(eski).

Starter code

main.go
package main

import (
    "fmt"
    "runtime"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "runtime"
)

func main() {
    eski := runtime.GOMAXPROCS(2)
    fmt.Println(runtime.GOMAXPROCS(0))
    runtime.GOMAXPROCS(eski)
}

Expected output

2

Questions and answers

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

1 In a CPU-bound program, what does raising <code>GOMAXPROCS</code> far above the core count do?

  • It doesn't speed up; it adds extra context switching Correct answer
  • It gives linear speed-up
  • It disables the GC
  • It resets memory use

Explanation: Real parallelism is bounded by the core count; extra Ps only add switching costs between OS threads.

2 Scheduler trace

Question
GODEBUG=____=1000 ./app
Answer
GODEBUG=schedtrace=1000 ./app

Explanation: schedtrace=1000 writes the scheduler state to stderr every 1000 ms.

3 Group summary

Term Meaning
Work stealing Load balancing
Preemption Fair time sharing
Handoff Keep P busy during syscalls
Netpoller Non-blocking network I/O

All lessons in Expert