Sobes.tech
Principal

What entities are present in the scheduler?

sobes.tech AI

Answer from AI

The Golang scheduler (M) consists of the following entities:

  • M (Machine): Represents an operating system thread. Responsible for executing G-code on the processor. M takes G from the local P queue or the run queue.
  • P (Processor): A logical processor (context). Contains a local queue of ready-to-run Gs. P is bound to M, and only one M can be bound to P at any time. The default number of P is GOMAXPROCS.
  • G (Goroutine): A lightweight thread of execution. Represents a concurrent function or method. G executes on P.
// Representation of a goroutine, contains a stack, a function pointer, and state.
type g struct {
	stack       stack     // stack describes the goroutine's stack
	stackguard  uintptr   // for stack checking
	stackbase   uintptr   // base of the stack
	sched stato     // for the scheduler
    // ... other fields
}
// Representation of a logical processor, has its own local goroutine queue
type p struct {
	id          int    // ID of the logical processor
	runq        []*g   // local queue of goroutines
	// ... other fields
}
// Representation of an OS thread, executes goroutines using p
type m struct {
	g0      *g    // scheduler goroutine
	curg    *g    // current goroutine
	p       *p    // bound logical processor
    // ... other fields
}

The interaction between entities is as follows:

  1. Goroutines (G) are placed in the local queues of logical processors (P).
  2. OS threads (M) take P and fetch Gs from their local queues for execution on the processor.
  3. If the local queue P is empty, M may attempt to steal G from another P's local queue (work-stealing).
  4. During blocking system calls, M detaches from P, and another M can take this P to execute other Gs. The blocked G remains attached to the detached M.
// Simplified illustration of scheduling:
// m0 ---(bound to)---> p0 ---> [g1, g2, g3] (local queue)
// m1 ---(bound to)---> p1 ---> [g4, g5]
// m2 (free) ---> searches for p0 or p1 to steal

Thus, the Golang scheduler efficiently utilizes available processor cores by distributing the execution of lightweight goroutines across OS threads via logical processors.