Home >Backend Development >Golang >How does the Go scheduler manage the creation of M and P in the presence of blocking operations?
Understanding M and P Creation in Go Scheduler
The Go scheduler operates on a model involving goroutines, OS threads (M), and contexts/processors (P). To optimize performance, the scheduler manages the creation and usage of M and P dynamically.
Creation of M
M is created when the scheduler detects a need to execute blocking tasks. In your example code, the goroutines perform blocking database operations, which will trigger the creation of additional M. The exact number of M created depends on the number of blocked goroutines and the available system resources.
Creation of P
P is created when a new goroutine is launched. However, the scheduler does not create a new P for each goroutine. Instead, it reuses existing P instances, maintaining a fixed number of P equal to the value of GOMAXPROCS, typically set to the number of available CPUs.
In Your Example Code
In your test code, you create 50 goroutines in two batches. Since the database operations are blocking, M will be created as needed to handle the blocking goroutines. However, because P instances are reused, only 8 P will be created, representing the number of virtual cores on your system.
More Resources
For further exploration of this topic, refer to these resources:
The above is the detailed content of How does the Go scheduler manage the creation of M and P in the presence of blocking operations?. For more information, please follow other related articles on the PHP Chinese website!