The Go program, along with the runtime, is managed and executed on multiple OS threads. The runtime uses a scheduler strategy known as M:N scheduler, which will schedule M number of goroutines on N number of OS threads. As a result, whenever we need to run or switch to a different goroutine, the context switching will be fast, and this also enables us to use multiple cores of the CPU for parallel computing.
A solid understanding of Go's runtime and scheduler would be quite interesting and useful, and now would be a good time to look at them in detail.
From the Go scheduler's perspective, there are primarily three entities:
- Goroutine (G)
- OS thread or machine (M)
- Context or processor (P)
Let's look at what they do. We will also be looking the partial struct definitions of these entities to provide a better idea of how scheduling is implemented...