Home  >  Article  >  Backend Development  >  How does the Go scheduler manage the creation of M and P in the presence of blocking operations?

How does the Go scheduler manage the creation of M and P in the presence of blocking operations?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-31 05:20:02491browse

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:

  • [Go Goroutine, OS Thread, and CPU Management](https://www.programming-books.net/2019/07/understand-go-scheduler-goroutine.html)
  • [Understanding the Go GMP (Goroutine-M-P) Model](https://blog.container-solutions.com/understanding-go-gmp-goroutine-m-p-model)

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn