Sobes.tech
Senior

What is a goroutine? How does it differ from a system thread? Tell me about the Go scheduler (GMP).

sobes.tech AI

Answer from AI

Goroutine is a lightweight thread of execution in the Go language, managed by the Go runtime rather than the operating system. Unlike system threads, goroutines have a much smaller stack size (starting from a few kilobytes and can grow dynamically), allowing thousands or even millions of goroutines to run concurrently with low overhead.

System threads are created and scheduled by the OS, have a fixed large stack, and involve more expensive context switch operations.

The Go scheduler is based on the GMP model:

  • G (goroutine) — the unit of execution.
  • M (machine) — a system thread (OS thread) on which goroutines run.
  • P (processor) — a logical processor, a resource needed to execute a goroutine on an M.

P manages a queue of ready-to-run goroutines (G). M can execute only one goroutine at a time, but with multiple Ms and Ps, the scheduler efficiently distributes goroutines across system threads, ensuring concurrency and parallelism.

This approach allows Go to efficiently utilize system resources and scale on multiprocessor systems.

What is a goroutine? How does it differ from a system… - sobes.tech