Sobes.tech
Senior

How does the Go scheduler work, what model is underneath? Have you ever had to configure the scheduler yourself?

sobes.tech AI

Answer from AI

The Go scheduler is based on an M:N model, where a set of goroutines (N) are mapped onto a smaller or equal number of system threads (M). It is based on the concept of three entities:

  • G (goroutine) — a lightweight thread of execution.
  • M (machine) — a system thread of the OS.
  • P (processor) — a logical processor that manages the execution of goroutines on M.

Each P has a queue of goroutines ready to run. M is bound to a P and executes goroutines from its queue. The scheduler balances the load, switches goroutines, and supports preemption (interrupting goroutines for fair time sharing).

Manual configuration of the scheduler is usually not required, but you can influence its behavior through the environment variable GOMAXPROCS, which sets the number of P (logical processors) available to the scheduler. This allows controlling the level of parallelism.

Example of setting the maximum number of logical processors:

import "runtime"

func main() {
    runtime.GOMAXPROCS(4) // limit parallelism to four threads
    // ...
}

In rare cases, you can use runtime/debug for more fine-tuned configuration, but the built-in scheduler is usually efficient enough and does not require intervention.