Sobes.tech
Middle+

Tell about the goroutine management pattern (GMP) in Go.

sobes.tech AI

Answer from AI

The Go scheduler manages goroutines, OS threads, and logical processors using the GMP model:

  • G (Goroutine): A lightweight, independent unit of execution. Contains a stack, instruction pointer, and other state information. Multiple goroutines can run on a single OS thread.
  • M (Machine): An OS thread. Acts as an executor that runs goroutine code. Multiple M can be available to the scheduler.
  • P (Processor): A logical processor. Provides a context for executing goroutines. Contains a local queue of goroutines ready to run on this M. The default number of P is runtime.NumCPU().

Interaction:

  1. A goroutine (G) is created and placed in a global or local P queue.
  2. A free M requests a P. If available, M is bound to it.
  3. M takes a goroutine from P's local queue and begins its execution.
  4. If the goroutine blocks (e.g., waiting for I/O), M detaches from P ("hand off"). P remains available for another M or plans another goroutine from its queue.
  5. When a blocked goroutine is ready to resume, it is placed back into P's queue or the global queue.
  6. M can be created by the scheduler if needed (e.g., if all existing M are blocked) or removed when inactive.

Preemption (forced switching): The scheduler can interrupt a goroutine after a certain period (time slice) to ensure fair distribution of CPU time among other goroutines.

Work Stealing: If P has exhausted goroutines in its local queue, it can attempt to "steal" goroutines from the global queue or other P queues.