Middle+
How do goroutines work under the hood (GMP model)?
sobes.tech AI
Answer from AI
In Go, goroutines are implemented through the GMP model, where:
- G (goroutine) — a lightweight thread of execution with its own stack and context.
- M (machine) — a system thread of the OS on which goroutines run.
- P (processor) — a logical processor that connects G and M, managing execution.
Operation of the model:
- P allocates M to execute goroutines.
- M executes G, switching between them as needed (for example, during blocking or waiting).
- The GMP scheduler balances the load, distributing goroutines across available M and P.
This allows efficient use of system threads while creating thousands of goroutines with minimal memory and context switch costs, as switching between goroutines occurs at the user level, not the OS kernel.
Example:
func main() {
go func() {
fmt.Println("Goroutine is running")
}()
time.Sleep(time.Second) // Wait for the goroutine to finish
}