Senior
What are goroutines in Go? How do they differ from OS threads? How does the Go scheduler (GMP model) work?
sobes.tech AI
Answer from AI
Goroutines are lightweight execution threads in the Go language, managed by the scheduler within the Go runtime rather than the operating system. They allow functions to run concurrently with minimal memory and context switch overhead.
Differences from OS threads:
- Goroutines are much lighter in resources (usually start with a 2 KB stack that grows dynamically).
- Scheduling of goroutines occurs in user space, not the OS kernel.
- Switching between goroutines is faster than between OS threads.
The Go scheduler is based on the GMP model:
- G (goroutine) — the unit of work, the goroutine itself.
- M (machine) — the system thread on which goroutines run.
- P (processor) — a logical processor that connects G and M, managing execution.
Scheduler operation:
- The number of P is limited by GOMAXPROCS (default is the number of CPUs).
- Each P can execute one goroutine G on one thread M.
- The scheduler distributes goroutines across available P and M, switching them during blocking or timeout.
Example of creating a goroutine:
go func() {
fmt.Println("Hello from goroutine")
}()
Thus, goroutines provide efficient concurrency with low overhead compared to OS threads.