


An in-depth analysis of the reasons why there is a GMP scheduling model in the Go language
Apr 14, 2023 pm 03:26 PMWhy does Go have a GMP scheduling model? The following article will introduce to you the reasons why there is a GMP scheduling model in the Go language. I hope it will be helpful to you!
#The GMP scheduling model is the essence of Go. It reasonably solves the efficiency problem of multi-threaded concurrent scheduling coroutines.
What is GMP
First of all, we must understand what each generation of GMP refers to.
- G: The abbreviation of Goroutine refers to coroutine, which runs on a thread.
- M: The abbreviation of Machine, that is, thead, thread, cyclic scheduling coroutine and execution.
- P: The abbreviation of Processor, refers to the processor, which stores coroutines in local queues and provides available coroutines that are not dormant for threads.
Threads M each hold When a processor P wants to obtain a coroutine, it is first obtained from P, so the GMP model diagram is as follows:
The general process is that thread M obtains it from P's queue If the coroutine cannot obtain it, it will compete for the lock from the global queue to obtain it.
Processor P
The coroutine G and thread M structures have been explained in the previous articles. Here we analyze the processor P.
Function
Processor P stores a batch of coroutines, so that thread M can obtain coroutines from them without locking, without having to compete with other threads for the global queue. Coroutine in the process, thereby improving the efficiency of scheduling coroutines.
Source code analysis
The source code of the p structure is in src\runtime\runtime2.go
, and some important fields are shown here.
type p struct { ... m muintptr // back-link to associated m (nil if idle) // Queue of runnable goroutines. Accessed without lock. runqhead uint32 runqtail uint32 runq [256]guintptr runnext guintptr ... }
m
is the thread to which the processorp
belongsrunq
is a queue that stores coroutinesrunqhead
,runqtail
represents the head and tail pointers of the queuerunnext
points to the next runnable coroutine
How do thread M and processor P cooperate?
In src\runtime\proc.go
, there is a schedule
method, which is the first function run by the thread. In this function, the thread needs to obtain a runnable coroutine. The code is as follows:
func schedule() { ... // 尋找一個可運行的協(xié)程 gp, inheritTime, tryWakeP := findRunnable() ... }
func findRunnable() (gp *g, inheritTime, tryWakeP bool) { // 從本地隊列中獲取協(xié)程 if gp, inheritTime := runqget(pp); gp != nil { return gp, inheritTime, false } // 本地隊列拿不到則從全局隊列中獲取協(xié)程 if sched.runqsize != 0 { lock(&sched.lock) gp := globrunqget(pp, 0) unlock(&sched.lock) if gp != nil { return gp, false, false } } }
Get the coroutine from the local queue
func runqget(pp *p) (gp *g, inheritTime bool) { next := pp.runnext // 隊列中下一個可運行的協(xié)程 if next != 0 && pp.runnext.cas(next, 0) { return next.ptr(), true } ... }
If there is no coroutine in the local queue or the global queue What should I do? Should I just let the thread idle like this?
At this time, processor P will steal tasks and steal some tasks from the local queues of other threads. This is called sharing the pressure of other threads and improving the utilization of its own threads.
The source code is in src\runtime\proc.go\stealWork
. If you are interested, you can take a look.
Where should the newly created coroutine be allocated?
Should the newly created coroutine be allocated to the local or global queue? Score:
- Go thinks that the new coroutine has a high priority, so it first looks for the local queue to put it in. Enter and jump in line.
- When the queue of this team is full, it will be put into the global queue.
The actual process is:
- Randomly search for P
- Put the new coroutine into P's
runnext
, which means The coroutine will be run next and the queue will be jumped. - If P's coroutine is full, it will be put into the global queue
The source code is in src\runtime\proc.go \newproc
function.
// Create a new g running fn. // Put it on the queue of g's waiting to run. // The compiler turns a go statement into a call to this. func newproc(fn *funcval) { gp := getg() pc := getcallerpc() systemstack(func() { newg := newproc1(fn, gp, pc) // 創(chuàng)建新協(xié)程 pp := getg().m.p.ptr() runqput(pp, newg, true) // 尋找本地隊列放入 if mainStarted { wakep() } }) }
Conclusion
This article initially introduces the GMP scheduling model, and specifically introduces how processor P and thread M obtain coroutines.
Processor P solves the problem of multi-thread mutual exclusion to obtain coroutines and improves the efficiency of scheduling coroutines. However, no matter whether coroutines are in local or global queues, it seems that they are only executed sequentially. So what about Go? How to implement asynchronous and concurrent execution of coroutines? Let’s continue the analysis in the next article (although no one will read it...).
Recommended learning: Golang tutorial
The above is the detailed content of An in-depth analysis of the reasons why there is a GMP scheduling model in the Go language. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Using bufio.Scanner is the most common and efficient method in Go to read files line by line, and is suitable for handling scenarios such as large files, log parsing or configuration files. 1. Open the file using os.Open and make sure to close the file via deferfile.Close(). 2. Create a scanner instance through bufio.NewScanner. 3. Call scanner.Scan() in the for loop to read line by line until false is returned to indicate that the end of the file is reached or an error occurs. 4. Use scanner.Text() to get the current line content (excluding newline characters). 5. Check scanner.Err() after the loop is over to catch possible read errors. This method has memory effect

The answer is: Go applications do not have a mandatory project layout, but the community generally adopts a standard structure to improve maintainability and scalability. 1.cmd/ stores the program entrance, each subdirectory corresponds to an executable file, such as cmd/myapp/main.go; 2.internal/ stores private code, cannot be imported by external modules, and is used to encapsulate business logic and services; 3.pkg/ stores publicly reusable libraries for importing other projects; 4.api/ optionally stores OpenAPI, Protobuf and other API definition files; 5.config/, scripts/, and web/ store configuration files, scripts and web resources respectively; 6. The root directory contains go.mod and go.sum

Routing in Go applications depends on project complexity. 1. The standard library net/httpServeMux is suitable for simple applications, without external dependencies and is lightweight, but does not support URL parameters and advanced matching; 2. Third-party routers such as Chi provide middleware, path parameters and nested routing, which is suitable for modular design; 3. Gin has excellent performance, built-in JSON processing and rich functions, which is suitable for APIs and microservices. It should be selected based on whether flexibility, performance or functional integration is required. Small projects use standard libraries, medium and large projects recommend Chi or Gin, and finally achieve smooth expansion from simple to complex.

Go's flag package can easily parse command line parameters. 1. Use flag.Type() to define type flags such as strings, integers, and booleans; 2. You can parse flags to variables through flag.TypeVar() to avoid pointer operations; 3. After calling flag.Parse(), use flag.Args() to obtain subsequent positional parameters; 4. Implementing the flag.Value interface can support custom types to meet most simple CLI requirements. Complex scenarios can be replaced by spf13/cobra library.

The if-else statement in Go does not require brackets but must use curly braces. It supports initializing variables in if to limit scope. The conditions can be judged through the elseif chain, which is often used for error checking. The combination of variable declaration and conditions can improve the simplicity and security of the code.

In Go, constants are declared using the const keyword, and the value cannot be changed, and can be of no type or type; 1. A single constant declaration such as constPi=3.14159; 2. Multiple constant declarations in the block are such as const(Pi=3.14159; Language="Go"; IsCool=true); 3. Explicit type constants such as constSecondsInMinuteint=60; 4. Use iota to generate enumeration values, such as const(Sunday=iota;Monday;Tuesday) will assign values 0, 1, and 2 in sequence, and iota can be used for expressions such as bit operations; constants must determine the value at compile time,

gorun is a command for quickly compiling and executing Go programs. 1. It completes compilation and running in one step, generates temporary executable files and deletes them after the program is finished; 2. It is suitable for independent programs containing main functions, which are easy to develop and test; 3. It supports multi-file operation, and can be executed through gorun*.go or lists all files; 4. It automatically processes dependencies and uses the module system to parse external packages; 5. It is not suitable for libraries or packages, and does not generate persistent binary files. Therefore, it is suitable for rapid testing during scripts, learning and frequent modifications. It is an efficient and concise way of running.

Go programs handle SIGTERM to achieve elegant exits, ensuring resource release and task ending. Use the os/signal package to listen for signals and pass them through channels, and implement cleaning logic in conjunction with context. 1. Create a channel and register the signal of interest with signal.Notify; 2. Receive the signal individually and trigger cancel the context; 3. The main goroutine waits for the context to complete and perform cleaning; 4. Notes include calling signal.Stop in time, the channel capacity is at least 1, and controlling the exit time in combination with the context timeout mechanism. In actual projects, a unified shutdown is always encapsulated.
