👨 🏫 GMP.

Simple understanding of GMS scheduling model principles.

The Autumn recruit has been started. From now on, we will start to output some experience for sharing. If you have better suggestions, we hope to contact Xiao ma for correction.

🔖 1. Some basic concepts.

  • G: Goroutine, a coroutine in Go, can be analogous to a coroutine in Java.
  • M: indicates that operating system threads can also be kernel threads. At the Go language level, you can think of M as a CPU kernel. It is represented by the runtime.m structure.
  • P: Logical processors at the Go language level, but not the actual number of cpus.

The OS thread is responsible for scheduling M, where the relationship is M:N, that is to say, M is switched. Each M is bound to a P, which schedules the corresponding G for execution

💡 special G and M

  • M0: the main thread that starts the main method. This M instance is stored in the runtime. M0 global variable and does not need to be allocated on the heap.
  • G0: Each time an M is started, a G is created. The first G created for each M is responsible for scheduling G, which does not refer to any executable function. Each M has its own G0.

🔖 2. Scheduling process.

  1. Global queue: holds G waiting for execution.
  2. Local queue of P: When a new G is created in the local queue, it is preferentially added to the local queue. When the local queue is full, the general G of the local queue is moved to the global queue. The number of G stored in the local queue cannot exceed 256.
  3. The list of P is initialized according to GOMAXPROCOS, but after a version of Go is actually created according to the number of CPU cores.

Scheduling process:

Go func creates a G object, which is stored in either a local queue or a global queue, P wakes up M, P continues to execute its program, M finds if there is a free P, if there is a free P, moves the G object to P itself, and then executes a scheduling loop. Call G objects to perform tasks, execute, clean up threads, and continue to find new G execution.

Context switch may occur at any time during the execution of M. When context switch occurs, the thread of execution needs to be protected for on-site reply when the execution is scheduled. The Go scheduler M’s stack is stored on the G object, and the G object only needs to save the registers required by M to the G object to achieve on-site protection.

Physical CPU core is responsible for scheduling OS operating system kernel thread to perform the corresponding logic code, the OS kernel thread is used for scheduling M, which is the corresponding proportion between M: N, OS responsible to thread scheduling M, and M is the language level threads in the abstract as a result, M G P scheduling (tasks) to perform the corresponding tasks to each other.

Welcome to pay attention to my public number: pony teach you to write Bug, write Bug interview together.