Golang naturally supports concurrency, and Goroutine is the main attraction of Go, which uses the CSP concurrent communication model. How does Go support high concurrency? This is where Golang’s MPG model comes in.

  1. M stands for a kernel thread, an M is a kernel thread, and goroutine runs on top of M

  2. P stands for Processor, and its main purpose is to execute a Goroutine, so it also maintains a runnable Goroutine queue, and a free Goroutine queue, which stores all the Goroutines it needs to execute.

  3. G represents the actual data structure of Goroutine and maintains the information required by Goroutine, such as the stack, program counters, and M where it resides.

  4. Sched represents a scheduler that maintains storage of idle M queues, idle P queues, runnable G queues, free G queues and some state information of the scheduler.

One diagram illustrates the MPG model:

The “groundhog” is M, the “cart” is P, and the “block” is G. There is a special groundhog in this picture, and that groundhog is Sched, the contractor.

From the picture, we can see that the “groundhog” is constantly carrying the “wooden block” to the “cart”, and then pushing it to burn. In this process may appear “groundhog” because of tired, and the speed of processing slowed, this time “contractor” appeared, “contractor” very considerate of the “groundhog” “cart” to other “groundhog” to deal with. If one groundhog had too many blocks in his cart, the contractor would ask the other groundhog to help him out. When the “contractor” found that the existing “groundhog” has been too busy, go back to find some new “groundhog” to come over, and give them a “cart”. Until all the “blocks” are burned.

Some of the situations mentioned above:

  1. A “groundhog” is a term used to describe time-consuming operations such as IO.

  2. Other groundhogs are called work stealing algorithms, which have been used in many languages, such as Fork/Foin in Java.

The default number of groundhogs in Golang is the number of CPU cores, and the groundhogs communicate through the CSP model.

References:

zhuanlan.zhihu.com/p/22352969