Skip to content
quboliu
Go back

Repost · Bilingual

Go SchedulerGo 调度器

Area: Go 语言Edit page

Contents目录

Disclaimer适用范围

This blog post primarily focuses on Go 1.24 programming language running on Linux on ARM architecture. It may not cover platform-specific details for other operating systems or hardware architectures.

本文主要讨论 ARM 架构的 Linux 上运行的 Go 1.24。其他操作系统或硬件架构可能有各自的实现细节,本文未必涉及。

The content is based on other sources and my own understanding of Go, so it might not be entirely accurate. Feel free to correct me or give suggestions in the comment section at the very bottom 😄.

文章依据参考资料和我自己对 Go 的理解写成,难免有不准确之处。欢迎在文末评论区指出问题,或提出建议 😄。

Introduction引言

⚠️ This post assumes that you already have a basic understanding of Go concurrency (goroutines, channels, etc.). If you’re new to these concepts, consider reviewing them before continuing.

⚠️ 阅读本文需要了解 Go 并发编程的基本概念,例如 goroutine 和 channel。如果还不熟悉,建议先了解这些概念再往下读。

Go or Golang, introduced in 2009, has steadily grown in popularity as a programming language for building concurrent applications. It is designed to be simple, efficient, and easy to use.

Go(也叫 Golang)于 2009 年问世,此后越来越多的人用它编写并发应用。它的设计目标是简洁、高效、易用。

Go’s concurrency model is built around the concept of goroutines, which are lightweight user threads managed by the Go runtime on user space. Go offers useful primitives for synchronization, such as channels, to help developers write concurrent code easily. It also uses non-trivial techniques to make I/O bound programs efficient.

Go 的并发模型以 goroutine 为基础。goroutine 是由 Go 运行时在用户空间管理的轻量级线程。Go 提供 channel 等同步原语,方便开发者编写并发代码,也在底层运用了一系列技术来提高 I/O 密集型程序的效率。

Understanding the Go scheduler is crucial for Go programmer to write efficient concurrent programs. It also helps us become better at troubleshooting performance issues or tuning the performance of our Go programs. In this post, we will explore how Go scheduler evolved over time, and how the Go code we write happens under the hood.

想写出高效的 Go 并发程序,或是在程序变慢时查找原因、调优性能,都需要理解调度器。本文会回顾 Go 调度器的演进,并追踪我们写下的 Go 代码在底层究竟如何执行。

Compilation and Go Runtime编译与 Go 运行时

This post covers a lot of source code walkthrough, so it is better to have a basic understanding of how Go code is compiled and executed first. When a Go program is built, there are three stages:

下文有不少源码走读,我们先了解 Go 代码怎样编译和执行。构建一个 Go 程序可以分为三个阶段。

Go 代码变成可执行文件的过程
How Go code is transformed into an executable binary file
Go 代码变成可执行文件的过程

To understand Go scheduler, you have to understand Go runtime first. Go runtime is the core of the programming language, providing essential functionalities such as scheduling, memory managements, and data structures. It’s nothing but a collection of functions and data structures that makes Go programs work. The implementation of Go runtime can be found in runtime package. Go runtime is written in a combination of Go and assembly code, with the assembly code primarily used for low-level operations such as dealing with registers.

要理解调度器,得先了解 Go 运行时。运行时是这门语言的核心,它用一组函数和数据结构提供调度、内存管理等基本功能,让 Go 程序运行起来。实现位于 runtime 包中,由 Go 和汇编共同编写。汇编主要负责操作寄存器等底层工作。

Go 运行时的作用
The role of Go runtime
Go 运行时的作用

Upon compiling, Go compiler replaces some keywords and built-in functions with Go runtime’s function calls. For example, the go keyword—used to spawn a new goroutine—is substituted with a call to runtime.newproc, or the new function—used to allocate a new object—is replaced with a call to runtime.newobject.

编译时,Go 编译器会把某些关键字和内置函数换成运行时函数调用。例如,用来创建 goroutine 的 go 关键字会变成对 runtime.newproc 的调用,用来分配新对象的 new 则会变成对 runtime.newobject 的调用。

You might be surprised to learn that some functions in the Go runtime have no Go implementation at all. For example, functions like getg are recognized by the Go compiler and replaced with low-level assembly code during compilation. Other function, such as gogo, are platform-specific and implemented entirely in assembly. It is the responsibility of the Go linker to connect these assembly implementations with their Go declarations.

有些运行时函数甚至没有 Go 语言实现。例如,编译器认识 getg,会在编译时将它直接替换成底层汇编指令。另一些函数因平台而异,如 gogo 完全由汇编实现。链接器负责把汇编实现与 Go 中的声明连接起来。

In some cases, a function appears to have no implementation in its package, but is actually linked to a definition in the Go runtime using the //go:linkname compiler directive. For instance, the commonly used time.Sleep function is linked to its actual implementation at runtime.timeSleep

有的函数在所属包中看似只有声明,其实通过编译器指令 //go:linkname 链接到了运行时中的定义。例如,常用的 time.Sleep 函数所对应的实现就是 runtime.timeSleep。

Primitive Scheduler早期调度器

⚠️ The Go scheduler isn’t a standalone object, but rather a collection of functions that facilitate the scheduling. Additionally, it doesn’t run on a dedicated thread; instead, it runs on the same threads that goroutines run on. These concepts will become clearer as you read through the rest of the post.

⚠️ Go 调度器由一组共同完成调度的函数构成。它没有专属线程,而是和 goroutine 在同一批线程上运行。读到后面,这两点就会更清楚。

If you’ve ever worked in concurrency programming, you might be familiar with multithreading models. It specifies how user-space threads (coroutines in Kotlin, Lua or goroutines in Go) are multiplexed onto single or multiple kernel threads. Typically, there are three models: many-to-one (N:1), one-to-one (1:1), and many-to-many (M:N).

熟悉并发编程的读者可能听说过多线程模型。它描述的是用户态线程(例如 Kotlin、Lua 的协程或 Go 的 goroutine)如何复用一个或多个内核线程。常见模型有三种:多对一(N:1)、一对一(1:1)和多对多(M:N)。

多对一线程模型
Many-to-one multithreading model1
多对一线程模型
一对一线程模型
One-to-one multithreading model2
一对一线程模型
多对多线程模型
Many-to-many multithreading model3
多对多线程模型

Go opts for the many-to-many (M:N) threading model, which allows multiple goroutines to be multiplexed onto multiple kernel threads. This approach sacrifices complexity to take advantage of multicore system and make Go program efficient with system calls, addressing the problems of both N:1 and 1:1 models. As kernel doesn’t know what goroutine is and only offers thread as concurrency unit to user-space application, it is the kernel thread that runs scheduling logic, executes goroutine code, and makes system call on behalf of goroutines.

Go 采用多对多(M:N)模型,让多个 goroutine 复用多个内核线程。实现虽然更复杂,却能利用多核系统,并在发生系统调用时保持效率,兼顾 N:1 和 1:1 模型各自难以解决的问题。内核只向用户态程序提供线程这一并发执行单位,并不知道 goroutine 的存在。执行调度逻辑、运行 goroutine 的代码、代它发起系统调用的,都是内核线程。

In the early days, particularly before version 1.1, Go implemented the M:N multithreading model in a naive way. There were only two entities: goroutines (G) and kernel threads (M, or machines). A single global run queue was used to store all runnable goroutines and guarded with lock to prevent race condition. The scheduler—running on every thread M—was responsible for selecting a goroutine from the global run queue and executing it.

早期 Go,特别是 1.1 以前,对 M:N 模型的实现很简单:系统里只有 goroutine(G)和内核线程(M,即 machine)。所有可运行的 goroutine 都放在一个全局运行队列中,由一把锁保护以避免竞态。每个线程 M 上都有调度器代码,负责从全局队列选出 goroutine 并执行。

Go 的早期调度器
Go’s primitive scheduler
Go 的早期调度器

Nowadays, Go is well-known for its performant concurrency model. Unfortunately, that’s not the case for the early Go. Dmitry Vyukov—one of the key Go contributors—pointed out multiple issues with this implementation in his famous Scalable Go Scheduler Design: “In general, the scheduler may inhibit users from using idiomatic fine-grained concurrency where performance is critical.” Let me explain in more detail what he meant.

如今 Go 的并发模型以高性能著称,早期的情况却不同。Go 的主要贡献者 Dmitry Vyukov 在设计文档 Scalable Go Scheduler Design 中指出了当时实现的多个问题。他写道:“总的来说,在性能至关重要的地方,调度器可能会让用户不敢采用符合 Go 惯用写法的细粒度并发。”下面具体看看这句话的含义。

Firstly, the global run queue was a bottleneck for performance. When a goroutine was created, threads had to acquire a lock to put it into the global run queue. Similarly, when threads wanted to pick up a goroutine from the global run queue, they also had to acquire the lock. You may know that locking is not free, it does have overhead with lock contention. Lock contention leads to performance degradation, especially in high-concurrency scenarios.

第一个瓶颈是全局运行队列。创建 goroutine 时,线程必须先拿锁才能将它入队;从队列里取一个 goroutine 来执行,同样要拿锁。加锁有代价。线程争用同一把锁时,性能就会下降,并发越高越明显。

Secondly, threads frequently handoff its associated goroutine to another thread. This cause poor locality and excessive context switch overhead. Child goroutine usually wants to communicate with its parent goroutine. Therefore, making child goroutine run on the same thread as its parent goroutine is more performant.

第二个问题是线程经常把自己关联的 goroutine 交给另一个线程,破坏了局部性,也带来过多的上下文切换。子 goroutine 往往要和父 goroutine 通信,让它们在同一个线程上执行通常更快。

Thirdly, as Go’s been using Thread-caching Malloc, every thread M has a thread-local cache mcache so that it can use for allocation or to hold free memory. While mcache is only used by Ms executing Go code, it is even attached with Ms blocking in a system call, which don’t use mcache at all. An mcache can take up to 2MB of memory, and it is not freed until thread M is destroyed. Because the ratio between Ms running Go code and all Ms can be as high as 1:100 (too many threads are blocking in system call), this could lead to excessive resource consumption and poor data locality.

第三个问题与内存有关。Go 采用 Thread-caching Malloc,每个线程 M 都有一个线程本地缓存 mcache,用来分配对象或暂存空闲内存。只有执行 Go 代码的 M 才用得上 mcache,但阻塞在系统调用中的 M 即使根本用不到 mcache,也一直带着它。一个 mcache 最多可占 2 MB,要等线程 M 销毁才会释放。大量线程阻塞时,执行 Go 代码的 M 可能只占全部 M 的百分之一。这既浪费资源,也会损害数据局部性。

Scheduler Enhancement调度器的改进

Now that you have a understanding of the issues with early Go scheduler, let’s examine some of the enhancement proposals to see how Go team addressed these issues so that we have a performant scheduler today.

了解早期调度器的问题之后,再来看几个改进方案。今天调度器的性能,正是从解决这些问题开始的。

Proposal 1: Introduction of Local Run Queue方案一:引入本地运行队列

Each thread M is equipped with a local run queue to store runnable goroutines. When a running goroutine G on thread M spawns a new goroutine G1 using the go keyword, G1 is added to M’s local run queue. If the local queue is full, G1 is instead placed in the global run queue. When selecting a goroutine to execute, M first checks its local run queue before consulting the global run queue. Thus, this proposal addresses the first and second issues as described in the last section.

为每个线程 M 配一个本地运行队列,用来存放可运行的 goroutine。假设 M 上的 G 通过 go 创建了 G1,就将 G1 加入 M 的本地队列;若队列已满,再放入全局运行队列。挑选下一个 goroutine 时,M 也先查本地,随后才查全局。这解决了上一节的前两个问题。

调度器改进方案一
Proposal 1 for scheduler enhancement
调度器改进方案一

However, it can’t resolve the third issue. When many threads M are blocked in system calls, their mcache stays attached, causing high memory usage by the Go scheduler itself, not to mention the memory usage of the program that we—Go programmers—write.

第三个问题仍在。大量线程 M 阻塞在系统调用中时,各自的 mcache 还是挂在线程上。单是调度器本身就会占用大量内存,还没算上我们写的程序。

It also introduces another performance problem. In order to avoid starving goroutines in a blocked M’s local run queue like M1 in the figure above, the scheduler should allow other threads to steal goroutine from it. However, with a large number of blocked threads, scanning all of them to find a non-empty run queue becomes expensive.

这个方案还引入了新的性能问题。为了让上图中 M1 这类阻塞线程的本地 goroutine 不至于一直挨饿,调度器需要允许其他线程从它的队列里窃取工作。但阻塞线程一多,想找到一个非空队列,就得付出很高的扫描成本。

Proposal 2: Introduction of Logical Processor方案二:引入逻辑处理器

This proposal is described in Scalable Go Scheduler Design, where the notion of logical processor P is introduced. By logical, it means that P pretends to execute goroutine code, but in practice, it is thread M associated with P that actually performs the execution. Thread’s local run queue and mcache are now owned by P.

Scalable Go Scheduler Design 描述了这个方案,引入逻辑处理器 P。“逻辑”的意思是,表面上看是 P 在执行 goroutine,实际执行代码的是与 P 关联的线程 M。原来属于线程的本地运行队列和 mcache 现在都归 P 所有。

This proposal effectively addresses open issues in the last section. As mcache is now attached to P instead of M and M is detached from P when G makes system call, the memory consumption stays low when there are a large number of Ms entering system calls. Also, as the number of P is limited, the stealing mechanism is efficient.

这解决了上一节遗留的问题。mcache 现在跟着 P 走;当 G 发起系统调用,M 就能与 P 分离。这样,即使很多 M 同时进入系统调用,内存占用也能维持在较低水平。由于 P 的数量有限,窃取工作也更高效。

调度器改进方案二
Proposal 2 for scheduler enhancement
调度器改进方案二

With the introduction of logical processors, the multithreading model remains M:N. But in Go, it is specifically referred to as the GMP model as there are three kinds of entities: goroutine, thread and processor.

引入逻辑处理器之后,线程模型仍是 M:N。由于其中有 goroutine、线程和处理器三类实体,Go 将其称为 GMP 模型。

GMP ModelGMP 模型

Goroutine: gGoroutine:g

When the go keyword is followed by a function call, a new instance of g, referred to as G, is created. G is an object that represents a goroutine, containing metadata such as its execution state, stack, and a program counter pointing to the associated function. Executing a goroutine simply means running the function that G references.

在函数调用前加上 go,运行时就会创建一个 g 实例,记作 G。这个对象代表一个 goroutine,记录其执行状态、栈和指向关联函数的程序计数器等元数据。所谓执行 goroutine,就是运行 G 所指向的函数。

When a goroutine finishes execution, it isn’t destroyed; instead, it becomes dead and is placed into the free list of the current processor P . If P’s free list is full, the dead goroutine is moved to the global free list. When a new goroutine is created, the scheduler first attempts to reuse one from the free list before allocating a new one from scratch. This recycling mechanism makes goroutine creation significantly cheaper than creating a new thread.

goroutine 执行结束时并不会被销毁。它进入 dead 状态,被放回当前处理器 P 的空闲列表;如果列表已满,则移入全局空闲列表。下次创建 goroutine 时,调度器优先尝试从空闲列表中复用一个,找不到才重新分配。这种回收机制让创建 goroutine 比新建线程便宜得多。

The figure and table below described the state machine of goroutines in the GMP model. Some states and transitions are omitted for simplicity. The actions that trigger state transitions will be described along the post.

下面的表和图描述 GMP 模型中 goroutine 的状态机。为便于理解,省略了部分状态和转换。触发这些转换的动作会在后文逐一说明。

StateDescription
IdleHas just been created, and not yet initialized
RunnableCurrently in run queue, and about to execute code
RunningNot in a run queue, and executing code
SyscallExecuting system call, and not executing code
WaitingNot executing code, and not in a run queue, e.g. waiting for channel
DeadCurrently in a free list, just exited, or just beiging initialized
状态说明
空闲刚刚创建,尚未初始化。
可运行已进入运行队列,等待执行代码。
运行中正在执行代码,不在运行队列中。
系统调用正在执行系统调用,未执行 Go 代码。
等待未执行代码,也不在运行队列中,例如正在等待 channel。
已停用刚退出并进入空闲列表,或刚开始初始化。
GMP 模型中的 goroutine 状态机
State machine of goroutines in GMP model
GMP 模型中的 goroutine 状态机

Thread: m线程:m

All Go code—whether it’s user code, the scheduler, or the garbage collector—runs on threads that are managed by the operating system kernel. In order for the Go scheduler to make threads work well in GMP model, m struct representing threads is introduced, and an instance of m is called M.

无论是用户代码、调度器还是垃圾收集器,Go 代码都运行在操作系统内核管理的线程上。运行时用 m 结构体在 GMP 模型中表示线程,m 的实例称为 M。

M maintains reference to the current goroutine G, the current processor P if M is executing Go code, the previous processor P if M is executing system call, and the next processor P if M is about to be created.

M 保存指向当前 goroutine G 的引用。它还记录自己执行 Go 代码时关联的当前 P、执行系统调用前使用的上一个 P,以及为即将创建的 M 准备的下一个 P。

Each M also holds reference to a special goroutine called g0, which runs on the system stack—the stack provided by the kernel to the thread. Unlike the system stack, a regular goroutine’s stack is dynamically sized; it grows and shrinks as needed. However, the operations for growing or shrinking a stack must themselves run on a valid stack. For this, the system stack is used. When the scheduler—running on an M—needs to perform stack management, it switches from the goroutine’s stack to the system stack. In addition to stack growth and shrinkage, operations like garbage collection and parking a goroutine also require execution on the system stack. Whenever a thread performs such operation, it switches to the system stack and executes the operation in the context of g0.

每个 M 还引用一个特殊的 goroutine,叫作 g0。它使用内核为线程提供的系统栈。常规 goroutine 的栈则可以按需增长和收缩,但调整栈本身的操作也需要在有效的栈上执行,这时就要用系统栈。运行在 M 上的调度器需要管理栈时,会从 goroutine 的栈切换到系统栈。除栈的伸缩外,垃圾收集、挂起 goroutine 等操作也需要在系统栈上执行。线程做这些事时会切换到系统栈,在 g0 的上下文中运行。

Unlike goroutine, threads run scheduler code as soon as M is created, therefore the initial state of M is running. When M is created or woken up, the scheduler guarantees that there is always an idle processor P so that it can be associated with M to run Go code. If M is executing system call, it will be detached from P (will be described in Handling System Calls section) and P might be acquired by another thread M1 to continues its work. If M can’t find a runnable goroutine from its local run queue, the global run queue, or netpoll (will be described in How netpoll Works section), it keeps spinning to steal goroutines from other processors P and from the global run queue again. Note that not all M enters spinning state, it does so only if the number of spinning threads is less than half of the number of busy processors. When M has nothing to do, rather than being destroyed, it goes to sleep and waits to be acquired by a another processor P1 later (described in Finding a Runnable Goroutine).

M 一创建就执行调度器代码,因此线程的初始状态是 running,这一点和 goroutine 不同。创建或唤醒 M 时,调度器会保证有一个空闲 P 与它关联,以便执行 Go 代码。M 进入系统调用后会与 P 分离,另一个线程 M1 便可能取得这个 P 继续工作(见系统调用的处理)。如果 M 从本地队列、全局队列和 netpoll(见netpoll 的工作原理)都找不到可运行的 goroutine,就会自旋,尝试从其他 P 窃取工作,再查全局队列。只有自旋线程数少于忙碌处理器数的一半时,M 才会进入自旋。如果实在无事可做,M 就睡眠,等另一个处理器 P1 来使用它,详见寻找可运行的 goroutine。

The figure and table below described the state machine of threads in the GMP model. Some states and transitions are omitted for simplicity. Spinning is a substate of idle, in which thread consumes CPU cycles to solely execute Go runtime code that steals goroutine. The actions that trigger state transitions will be described along the post.

下面的表和图描述线程的状态机,同样省略了部分状态和转换。自旋是空闲的一种子状态:线程会消耗 CPU 周期,但只执行运行时中负责窃取 goroutine 的代码。触发状态转换的动作将在后文说明。

StateDescription
RunningExecuting Go runtime code, or user Go code
SyscallCurrently executing (blocking in) a system call
SpinningStealing goroutine from other processors
SleepSleeping, not consuming CPU cycle
状态说明
运行中正在运行 Go 运行时代码或用户的 Go 代码。
系统调用正在执行系统调用,可能阻塞在调用中。
自旋正在从其他处理器窃取 goroutine。
睡眠正在睡眠,不消耗 CPU 周期。
GMP 模型中的线程状态机
State machine of threads in GMP model
GMP 模型中的线程状态机

Processor: p处理器:p

p struct conceptually represents a physical processor to execute goroutines. Instances of p are called P, and they are created during the program’s bootstrap phase. While the number of threads created could be large (10000 in Go 1.24), the number of processors is usually small and determined by the GOMAXPROCS. There are exactly GOMAXPROCS processors, regardless of its state.

从概念上说,p 结构体代表一个执行 goroutine 的物理处理器。p 的实例称为 P,在程序启动阶段创建。线程数量可以很大(Go 1.24 的默认上限为 10000),但处理器通常只有少量几个,数量由 GOMAXPROCS 决定。无论这些处理器分别处于什么状态,总数都是 GOMAXPROCS。

To minimize lock contention on the global run queue, each processor P in the Go runtime maintains a local run queue. A local run queue is not just a queue but composed of two components: runnext which holds a single prioritized goroutine, and runq which is a queue of goroutines. Both of these components serve as a source of runnable goroutines for P, but runnext exists specifically as a performance optimization. The Go scheduler allows P to steal goroutines from other processors P1’s local run queue. P1’s runnext in only consulted if the first three attempts stealing from its runq is unsuccessful. Therefore, when P wants to execute a goroutine, there is less lock contention if it looks for a runnable goroutine from its runnext first.

为减少全局运行队列上的锁争用,每个 P 都有本地运行队列。它由两部分组成:runnext 是只放一个 goroutine 的优先槽位,runq 则是可容纳多个 goroutine 的队列。两处都能为 P 提供可运行的 goroutine,单设 runnext 是为了优化性能。Go 允许 P 从另一个处理器 P1 的本地队列窃取 goroutine。只有前三轮尝试都没能从 P1 的 runq 窃取到工作,才会考虑它的 runnext。因此,P 要执行 goroutine 时,先查自己的 runnext,争用会更少。

The runq component of P is an array-based, fixed-size, and circular queue. By array-based and fixed-size with 256 slots, it allows better cache locality and reduces memory allocation overhead. Fixed-size is safe for P’s local run queues as we also have the global run queue as a backup. By circular, it allows efficiently adding and removing goroutines without needing to shift elements around.

P 的 runq 是用数组实现的定长循环队列。数组固定为 256 个槽位,有利于缓存局部性,也减少了内存分配的开销。本地队列可以固定长度,因为还有全局队列兜底。循环结构让入队、出队都不需要搬移其他元素。

mcache serves as the front-end in Thread-Caching Malloc model and is used by P to allocate micro and small objects. pageCache, on the other hand, enables the memory allocator to fetch memory pages without acquiring the heap lock, thereby improving performance under high concurrency.

在 Thread-Caching Malloc 模型中,mcache 是分配器的前端。P 用它分配微小对象和小对象。pageCache 则让内存分配器可以不获取堆锁就取得内存页,改善高并发时的性能。

In order for a Go program to work well with sleeps, timeouts or intervals, P also manages timers implemented by min-heap data structure, where the nearest timer is at the top of the heap. When looking for a runnable goroutine, P also checks if there are any timers that have expired. If so, P adds the corresponding goroutine with timer to its local run queue, giving chance for the goroutine to run.

为了支持休眠、超时和周期性触发,P 还通过最小堆管理定时器,最早到期的定时器位于堆顶。寻找可运行的 goroutine 时,P 会一并检查定时器。如果有定时器到期,就将对应的 goroutine 加入本地运行队列,让它有机会执行。

The figure and table below described the state machine of processors in the GMP model. Some states and transitions are omitted for simplicity. The actions that trigger state transitions will be described along the post.

下面的表和图描述 GMP 模型中的处理器状态机,略去了部分状态和转换。后文会说明触发转换的动作。

StateDescription
IdleNot executing Go runtime code or user Go code
RunningAssociated with a M that is executing user Go code
SyscallAssociated with a M that is executing system call
GCStopAssociated with a M that is stopped-the-world for garbage collection
DeadNo longer in-used, waiting to be reused when GOMAXPROCS grows
状态说明
空闲既未执行 Go 运行时代码,也未执行用户的 Go 代码。
运行中与正在执行用户 Go 代码的 M 关联。
系统调用与正在执行系统调用的 M 关联。
垃圾收集停顿与因垃圾收集而暂停执行的 M 关联,处于全局停顿状态。
已停用已停用,等待 GOMAXPROCS 增大后复用。
GMP 模型中的处理器状态机
State machine of processors in GMP model
GMP 模型中的处理器状态机

At the early execution of a Go program, there are GOMAXPROCS processors P in the idle state. When a thread M acquires a processor to run user Go code, P transitions to the running state. If the current goroutine G makes a system call, P is detached from M and enters the syscall state. During the system call, if P is seized by sysmon (see Non-cooperative Preemption), it first transitions to idle, then is handed off to another thread (M1) and enters the running state. Otherwise, once the system call completes, P is reattached to last M and resumes the running state (see Handling system calls). When a stop-the-world garbage collection occurs, P transitions to the gcStop state and returns to its previous state once start-the-world resumes. If GOMAXPROCS is decreased at runtime, redundant processors transition to the dead state and are reused if GOMAXPROCS increases later.

Go 程序刚开始运行时,有 GOMAXPROCS 个 P 处于 idle 状态。线程 M 取得处理器以执行用户代码时,P 转入 running 状态。如果当前 G 发起系统调用,P 就与 M 分离并转入 syscall 状态。系统调用期间,如果 sysmon 收回 P(见非协作式抢占),P 会先转入 idle,再交给另一个线程 M1,转回 running。否则,系统调用结束时,P 重新与原来的 M 关联,恢复 running(见系统调用的处理)。发生全局停顿(STW)以进行垃圾收集时,P 进入 gcStop 状态,程序恢复执行时再回到先前的状态。如果运行中调小 GOMAXPROCS,多余的处理器会进入 dead 状态,日后调大 GOMAXPROCS 时可重新使用。

Program Bootstrap程序启动

To enable the Go scheduler, it must be initialized during the program’s bootstrap. This initialization is handled in assembly via the runtime·rt0_go function. During this phase, thread M0 (representing the main thread) and goroutine G0 (M0’s system stack goroutine) are created. Thread-local storage (TLS) for the main thread is also set up, and the address of G0 is stored in this TLS, allowing it to be retrieved later via getg.

程序启动时必须先初始化调度器。入口是汇编函数 runtime·rt0_go。这一阶段会创建代表主线程的 M0,以及使用 M0 系统栈的 goroutine G0。运行时还会为主线程设置线程本地存储(TLS),并把 G0 的地址存进去,之后可通过 getg 取回。

The bootstrap process then invokes the assembly function runtime·schedinit, whose Go implementation can be found at runtime.schedinit. This function performs various initializations, most notably invoking procresize, which sets up to GOMAXPROCS logical processors P in idle state. The main thread M0 is then associated with the first processors, transitioning its state from idle to running to execute goroutines.

接下来,启动代码在汇编中调用 runtime·schedinit,其 Go 实现是 runtime.schedinit。它负责多项初始化工作,其中最重要的是通过 procresize 建立 GOMAXPROCS 个处于 idle 状态的逻辑处理器 P。主线程 M0 随后与第一个处理器关联,后者从 idle 转入 running,开始执行 goroutine。

Afterward, the main goroutine is created to run runtime.main function, which serves as the Go runtime entry point. Within the runtime.main function, a dedicated thread is created to launch sysmon, which will be described in Non-cooperative Preemption section. Note that runtime.main is different from the main function that we write; the latter appears in the runtime as main_main.

运行时接着创建主 goroutine,用于执行 Go 运行时的入口函数 runtime.main。runtime.main 会创建一个专用线程来启动 sysmon,详见非协作式抢占。注意,runtime.main 与我们编写的 main 不是同一个函数,后者在运行时源码中以 main_main 的名字出现。

The main thread then calls mstart to begin execution on M0, starting the schedule loop to pick up and execute the main goroutine. In the runtime.main, after additional initialization steps, control is finally handed off to the user-defined main_main function, where the program begins executing user Go code.

主线程随后调用 mstart,让 M0 进入调度循环,取出主 goroutine 执行。在 runtime.main 完成其他初始化之后,控制权终于交给用户定义的 main_main,程序从这里开始执行用户的 Go 代码。

It’s worth noting that the main thread, M0, is responsible not only for running the main goroutine but also for executing other goroutines. Whenever the main goroutine is blocked—such as waiting for a system call or while waiting on a channel—the main thread looks for another runnable goroutine and execute it.

主线程 M0 除了运行主 goroutine,也可以执行别的 goroutine。当主 goroutine 因系统调用或等待 channel 等原因阻塞时,主线程会寻找另一个可运行的 goroutine 来执行。

Summing it up, when the program starts, there is one goroutine G executing the main function; two threads—one is the main thread M0, and the other is created to launch sysmon; one processor P0 in running state, and GOMAXPROCS−1 processors in idle state. The main thread M0 is initially associated with processor P0 to run the main goroutine G.

总结一下这里的启动场景:一个 goroutine G 执行 main;两个线程分别是主线程 M0 和用于启动 sysmon 的线程;一个处理器 P0 处于 running 状态,另外 GOMAXPROCS−1 个处于 idle 状态。最初 M0 关联的是 P0,在它上面运行主 goroutine。

The figure below illustrates the program’s state at startup. It assumes that GOMAXPROCS is set to 2 and that the main function has just started. Processor P0 is executing the main goroutine and is therefore in running state. Processor P1 is not executing any goroutine and is in idle state. While the main thread M0 is associated with processor P0 to execute main goroutine, another thread M1 is created to run sysmon.

下图假设 GOMAXPROCS 为 2,main 刚刚开始执行。P0 正在运行主 goroutine,处于 running 状态。P1 暂时没有执行任何 goroutine,处于 idle 状态。主线程 M0 与 P0 关联,另一个线程 M1 则负责运行 sysmon。

GMP 模型中的程序启动过程
Program bootstrap in GMP model
GMP 模型中的程序启动过程

It’s worth to mention that during the bootstrap phase, the runtime also spawns several other goroutines related to memory management, such as marking, sweeping and scavenging. However, we’ll leave those out of scope for this post. They’ll be explored in greater detail in a future article.

启动期间,运行时还会创建一些管理内存的 goroutine,分别负责标记、清扫和向操作系统归还内存等工作。这里暂不展开,留待以后的文章细说。

Creating a Goroutine创建 goroutine

Go offers us a simple API to start a concurrent execution unit: go func() { ... } (). Under the hood, Go runtime does a lot complicated work to make it happen. The go keyword is just a syntactic sugar for Go runtime newproc function, which is responsible for scheduling a new goroutine. This function essentially does 3 things: initialize the goroutine, put it into the run queue of the processor P which the caller goroutine is running on, wake up another processor P1.

Go 用很简单的语法就能启动一个并发执行单元:go func() { ... } ()。为此,运行时在幕后做了不少工作。go 关键字是运行时函数 newproc 的语法糖。这个函数负责调度新 goroutine,主要做三件事:初始化它,把它放入调用方所在处理器 P 的运行队列,再尝试唤醒另一个处理器 P1。

Initializing Goroutine初始化 goroutine

When newproc is called, it creates a new goroutine G only if there are no idle goroutines available. Goroutines become idle after they return from execution. The newly created goroutine G is initialized with a 2KB stack, as defined by the stackMin constant in Go runtime. Additionally, goexit—which handles cleanup logic and scheduling logic—is pushed onto G’s call stack to ensure it is executed when G returns. After initialization, G transitions from dead state to runnable state, indicating that it’s ready to be scheduled for execution.

goroutine 执行返回后可以被复用。调用 newproc 时,只有找不到可复用的 goroutine 才会创建一个新的 G。新 goroutine 的初始栈为 2 KB,由运行时常量 stackMin 定义。运行时还会将负责清理和后续调度的 goexit 压入 G 的调用栈,保证 G 返回时执行它。初始化结束后,G 从 dead 转入 runnable,已经可以接受调度。

Putting Goroutine into Queue将 goroutine 放入队列

As mentioned earlier, each processor P has a run queue composed of two parts: runnext and runq. When a new goroutine is created, it is placed in runnext. If runnext already contains a goroutine G1, the scheduler attempts to move G1 to runq—provided runq is not full—and put G into runnext. If runq is full, G1 along with half of the goroutines in runq are moved to the global run queue to reduce the workload for P.

每个 P 的运行队列分为 runnext 和 runq。新创建的 goroutine 先放入 runnext。如果 runnext 中已经有 G1,调度器就尝试将 G1 移入 runq;只要 runq 还有空间,就能放下 G1,并把新的 G 写入 runnext。如果 runq 已满,就将 G1 和 runq 中的一半 goroutine 一起移入全局运行队列,减轻 P 的负担。

Waking Up Processor唤醒处理器

When a new goroutine is created, and we aim to maximize program concurrency, the thread which goroutine is running on attempts to wake up another processor P by futex system call. To do this, it first checks for any idle processors. If an idle processor P is available, a new thread is either created or an existing one is woken up to enter the schedule loop, where it will look for a runnable goroutine to execute. The logic for creating or reusing thread is described in Start Thread section.

为了让新创建的 goroutine 尽可能与现有工作并行,当前线程会尝试借助 futex 系统调用唤醒另一个处理器。它先检查是否有空闲的 P。如果有,要么创建一个新线程,要么唤醒已有线程,让它进入调度循环寻找可运行的 goroutine。创建或复用线程的逻辑见启动线程。

As previously mentioned, GOMAXPROCS—the number of active processors P—dictates how many goroutines can run concurrently. If all processors are busy and new goroutines keep spawning, neither existing thread is woken up nor new thread is created.

能同时执行多少个 goroutine,取决于活跃处理器数 GOMAXPROCS。如果所有 P 都忙,即使 goroutine 仍在不断创建,运行时也不会因此唤醒旧线程或创建新线程。

Putting It All Together串起整个创建过程

The figure below illustrates the process of how goroutines are created. For simplicity, it assumes GOMAXPROCS is set to 2, processor P1 hasn’t entered the schedule loop yet, and main function does nothing but keeps spawning new goroutines. Since goroutines don’t execute system call (discussed in Handling System Calls section), there is exactly one additional thread M2 is created to associate with processor P1.

下图演示 goroutine 的创建过程。为便于说明,假设 GOMAXPROCS 为 2,P1 尚未进入调度循环,main 除了不断创建 goroutine 什么也不做。假设这些 goroutine 都不执行系统调用(见系统调用的处理),整个过程就只需额外创建一个线程 M2,与 P1 关联。

GMP 模型中 goroutine 的创建过程
How goroutines are created in GMP model
GMP 模型中 goroutine 的创建过程

Schedule Loop调度循环

The schedule function in the Go runtime is responsible for finding and executing a runnable goroutine. It is invoked in various scenarios: when a new thread is created, when Gosched is called, when a goroutine is parked or preempted, or after a goroutine completes a system call and returns.

运行时的 schedule 函数负责寻找并执行可运行的 goroutine。新线程启动、调用 Gosched、goroutine 被挂起或抢占,以及 goroutine 完成系统调用并返回时,都有机会走到这个函数。

The process of selecting a runnable goroutine is complex and will be detailed in the Finding a Runnable Goroutine section. Once a goroutine is selected, it transitions from runnable to running state, signaling that it’s ready to run. At this point, a kernel thread invokes the gogo function to begin goroutine execution.

选择可运行 goroutine 的逻辑较为复杂,详见寻找可运行的 goroutine。一旦被选中,goroutine 就从 runnable 转入 running,接着内核线程会调用 gogo 开始执行它。

But why is it called a loop? As described in the Initializing Goroutine section, when a goroutine completes, the goexit function is invoked. This function eventually leads to a call to goexit0, which performs cleanup for the terminating goroutine and re-enters the schedule function—bringing the schedule loop back.

为什么叫“循环”?如初始化 goroutine所述,一个 goroutine 运行结束时会调用 goexit。沿调用链最终到达 goexit0,清理即将退出的 goroutine,然后再次进入 schedule。这就回到了调度循环的起点。

The following diagram illustrates the schedule loop in Go runtime, where pink blocks happen in user Go code and yellow blocks happen in the Go runtime code. Although the following may seem obvious, please note that the schedule loop is executed by thread. That’s why it happens after thread initialization (the blue block).

下图中,粉色方块代表用户 Go 代码,黄色方块代表 Go 运行时代码。读图时记住,执行调度循环的是线程,因此循环出现在蓝色的线程初始化阶段之后。

Go 运行时的调度循环
The schedule loop in Go runtime
Go 运行时的调度循环

But if the main thread is stuck in schedule loop, how can the process exit? Just take a look at the main function in Go runtime, which is executed by main goroutine. After main_main—alias of the main function that Go programmers write—returns, exit system call is invoked to terminate the process. That’s how the process can exit and the reason why the main goroutine doesn’t wait for goroutines spawned by go keyword.

如果主线程一直在调度循环里,进程怎么退出?看一下主 goroutine 执行的运行时 main 函数。用户编写的 main 在这里名为 main_main,它返回后,运行时会发起 exit 系统调用来终止进程。这也解释了为什么主 goroutine 不会等 go 关键字启动的其他 goroutine 全部结束。

Finding a Runnable Goroutine寻找可运行的 goroutine

It is the thread M’s responsibility to find a suitable runnable goroutine so that goroutine starvation can be minimized. This logic is implemented in the findRunnable, which is called by the schedule loop.

线程 M 负责选择合适的可运行 goroutine,尽量避免有 goroutine 长期得不到执行。这段逻辑位于 findRunnable,由调度循环调用。

Thread M looks for a runnable goroutine the following order, stopping the chain if it finds one:

M 按照下面的顺序寻找工作,任何一步找到可运行的 goroutine 就停止查找。

  1. Check trace reader goroutine’s availability (used in Non-cooperative Preemption section).
    检查跟踪读取 goroutine 是否可用,非协作式抢占一节会用到它。
  2. Check garbage collection worker goroutine’s availability (described in Garbage Collector section).
    检查垃圾收集工作 goroutine 是否可用,详见垃圾收集器。
  3. 1/61 of the time, check the global run queue.
    每 61 次调度中有一次先检查全局运行队列。
  4. Check local run queue of the associated processor P if M is spinning.
    如果 M 正在自旋,检查所关联 P 的本地运行队列。
  5. Check the global run queue again.
    再次检查全局运行队列。
  6. Check netpoll for I/O ready goroutine (described in How netpoll Works section).
    检查 netpoll 是否有等待的 I/O 已就绪的 goroutine,详见netpoll 的工作原理。
  7. Steal from other processors P1’s local run queue.
    从其他处理器 P1 的本地队列窃取工作。
  8. Check garbage collection worker goroutine’s availability again.
    再次检查垃圾收集工作 goroutine 是否可用。
  9. Check the global run queue again if M is spinning.
    如果 M 正在自旋,再查一次全局运行队列。

Step 1, 2 and 8 are for Go runtime internal use only. In step 1, trace reader is used for tracing the execution of the program. You will see how it’s used in the Goroutine Preemption section later. Meanwhile, step 2 and 8 allow the garbage collector to run concurrently with the regular goroutines. Although these steps don’t contribute to “user-visible” progress, they are essential for the Go runtime to function properly.

步骤 1、2 和 8 为运行时内部服务。步骤 1 的 trace reader 用于跟踪程序执行,后面的goroutine 抢占一节会演示其用法。步骤 2 和 8 让垃圾收集器有机会与普通 goroutine 并发执行。虽然用户看不到这些步骤直接推进自己的业务,它们却是运行时正常工作所必需的。

Step 3, 5 and 9 don’t just take one goroutine but attempts to grab a batch for better efficiency. The batch size is calculated as (global_queue_size/number_of_processors)+1, but it’s limited by several factors: it won’t exceed the specified maximum parameter, and won’t take more than half of the P’s local queue capacity. After determining how many to take, it pops one goroutine to return directly (which will be run immediately) and puts the rest into the P’s local run queue. This batching approach helps with load balancing across processors and reduces contention on the global queue lock, as processors don’t need to access the global queue as frequently.

步骤 3、5 和 9 会尝试成批取出 goroutine,以提高效率。批量大小按 (global_queue_size/number_of_processors)+1 计算,既不能超过调用方指定的上限,也不能超过 P 本地队列容量的一半。确定数量后,先弹出一个直接返回并执行,其余放入本地队列。这样既能在处理器之间平衡工作量,也能减少处理器访问全局队列的次数,降低锁争用。

Step 4 is a bit more tricky because the local run queue of P contains two parts: runnext and runq. If runnext is not empty, it returns the goroutine in runnext. Otherwise, it checks runq for any runnable goroutine and dequeue it. Step 6 will be described in detail in How netpoll Works section.

步骤 4 稍复杂,因为 P 的本地队列有 runnext 和 runq 两部分。如果 runnext 非空,就返回其中的 goroutine;否则检查 runq 并从队列中取出一个。步骤 6 留到netpoll 的工作原理详述。

Step 7 is the most complex part of the process. It attempts up to four times to steal work from another processor, referred to as P1. During the first three attempts, it tries to steal goroutines only from P1’s runq. If successful, half of the goroutines from P1’s runq are transferred to the current processor P’s runq. On the last attempt, it first tries to steal from P1’s runnext slot—if available—before falling back to P1’s runq.

步骤 7 最复杂。调度器最多尝试四轮,从另一个处理器 P1 窃取工作。前三轮只尝试从 P1 的 runq 窃取;成功时,将其中一半 goroutine 转到当前处理器 P 的 runq。按本文的描述,最后一轮会尝试取 P1 的 runnext 槽位,若没有可取的 goroutine,再回到 P1 的 runq。

Note that findRunnable not only finds a runnable goroutine but also wakes up goroutine that went into sleep before step 1 happens. Once the goroutine wakes up, it’ll be put into the local run queue of the processor P that was executing it, waiting to be picked up and executed by some thread M.

findRunnable 除了找可运行的 goroutine,还会在步骤 1 之前唤醒之前进入睡眠的 goroutine。醒来的 goroutine 会被放进原先执行它的 P 的本地运行队列,等待某个线程 M 选中并运行。

If no goroutine is found after step 9, thread M waits on netpoll until the nearest timer expires—such as when a goroutine wakes up from sleep (since sleeping in Go internally creates a timer). Why is netpoll involved with timers? This is because Go’s timer system heavily relies on netpoll, as noted in this code comment. After netpoll returns, M re-enters the schedule loop to search for a runnable goroutine again.

如果走完步骤 9 仍无收获,M 会等待 netpoll,直到最近的定时器到期。例如,Go 中的休眠会在内部创建定时器,到期后 goroutine 就能醒来。为什么定时器和 netpoll 有关?这段源码注释说明了 Go 的定时器系统对 netpoll 的依赖。netpoll 返回后,M 重新进入调度循环寻找工作。

The previous two behaviors of findRunnable allows the Go scheduler to wake up asleep goroutines, allowing the program to continue executing. They explain why every goroutine including the main one has chance to run after falling asleep. Let’s see how the following Go program works in another post 😄.

findRunnable 的上述两种行为使调度器能够唤醒休眠的 goroutine,让程序继续执行。这也解释了为什么包括主 goroutine 在内的各个 goroutine 睡醒之后都有机会运行。下面这个 Go 程序究竟如何工作,留到另一篇文章再看 😄。

package main

import "time"

func main() {
    go func() {
        time.Sleep(time.Second)
    }()
	
    time.Sleep(2*time.Second)
}

If P has no timer, its corresponding thread M will go idle. P is placed into idle list, M goes to sleep by calling the stopm function. It remains asleep until another M1 thread wakes it up, typically upon the creation of a new goroutine, as explained in Waking Up Processor. Once awakened, M reenters the schedule loop to search for and execute a runnable goroutine.

如果 P 没有定时器,对应的 M 将转为空闲。P 被放入空闲列表,M 调用 stopm 进入睡眠,直到另一个线程 M1 将它唤醒。这通常发生在创建新 goroutine 时,见唤醒处理器。醒来后,M 再次进入调度循环,寻找并执行可运行的 goroutine。

Goroutine PreemptionGoroutine 抢占

Preemption is the act of temporarily interrupting a goroutine execution to allow other goroutines to run, preventing goroutine starvation. There are two types of preemption in Go:

抢占是暂时中断某个 goroutine 的执行,让其他 goroutine 也有机会运行,避免它们长期饥饿。Go 中有两种抢占方式。

Let’s see how these two types of preemption work in Go.

下面分别看这两种方式如何工作。

Non-cooperative Preemption非协作式抢占

Let’s take an example to understand how non-cooperative preemption works. In this program, we have two goroutines that calculate the Fibonacci number, which is a tight loop with CPU intensive operations. In order to make sure that only one goroutine can run at a time, we set the maximum number of logical processors to 1 using GOMAXPROCS when running the program: GOMAXPROCS=1 go run main.go.

以下面的程序为例。两个 goroutine 都在计算斐波那契数,持续执行密集的 CPU 运算。为确保同一时刻只有一个 goroutine 能运行,启动时通过 GOMAXPROCS 将逻辑处理器的上限设为 1:GOMAXPROCS=1 go run main.go。

package main

import (
    "runtime"
    "time"
)

func fibonacci(n int) int {
    if n <= 1 {
        return n
    }   
    previous, current := 0, 1
    for i := 2; i <= n; i++ {
        previous, current = current, previous+current
    }
    return current
}

func main() {
    go fibonacci(1_000_000_000)
    go fibonacci(2_000_000_000)

    time.Sleep(3*time.Second)
}

Because there is exactly one processor P, there are many cases that could happen. One, neither goroutine runs because the main function has taken control of P. Two, one goroutine runs while the other is starved of execution. Three, somehow both goroutines run concurrently—almost magically.

只有一个 P,直觉上有几种可能:主函数一直占着它,两个 goroutine 谁也跑不了;只有一个能运行,另一个挨饿;或者看似不可思议,两个 goroutine 竟都能取得进展。

Fortunately, Go does support us to get the idea of what is happening with the scheduling. The runtime/trace package contains a powerful tool for understanding and troubleshooting Go programs. To use it, we need to add instrument to the main method to export the traces to file.

好在 Go 能让我们观察实际发生的调度。runtime/trace 包提供了理解 Go 程序执行过程、排查问题的工具。先在 main 中加入跟踪代码,把记录写到文件。

func main() {
    file, _ := os.Create("trace.out")
    _ = trace.Start(file)
    defer trace.Stop()
    ...
}

After the program finishes running, we use the command go tool trace trace.out to visualize the trace. I have prepared the trace.out file here just in case you want to play with it. In the figure below, the horizontal axis represents which goroutine is running on P at a given time. As expected, there is only one logical processor P named “Proc 0”, resulted from GOMAXPROCS=1.

程序结束后,执行 go tool trace trace.out 即可查看跟踪结果。想自己试一试,也可以下载示例 trace.out 文件。下图沿水平方向展示各时刻哪个 goroutine 正在 P 上运行。正如预期,GOMAXPROCS=1 意味着图中只有一个逻辑处理器“Proc 0”。

程序刚启动时的执行跟踪
Trace visualization when program starts
程序刚启动时的执行跟踪

By zooming in (pressing ‘W’) to the start of the timeline, you can see that the process begins with main.main (the main function in the main package), which runs on the main goroutine, G1. After a few microseconds, still on Proc 0, goroutine G10 is scheduled to execute the fibonacci function, taking over the processor and preempting G1.

按 W 键放大时间线起点,可以看到进程从主 goroutine G1 上的 main.main(main 包的 main 函数)开始。几微秒后,G10 被调度来执行 fibonacci,同样运行在 Proc 0 上,抢占了 G1 使用的处理器。

发生非协作式抢占时的执行跟踪
Trace visualization when non-cooperative preemption happens
发生非协作式抢占时的执行跟踪

By zooming out (pressing ‘S’) and scrolling slightly to the right, it can be observed that G10 is later replaced by another goroutine, G9, which is the next instance running the fibonacci function. This goroutine is also executed on Proc 0. Pay attention to runtime.asyncPreempt:47 in the figure, I will explain this in a moment.

按 S 键缩小,再向右稍稍移动时间线,可以看到 G10 后来被另一个 goroutine G9 替换。G9 是另一个执行 fibonacci 的实例,也在 Proc 0 上运行。留意图中的 runtime.asyncPreempt:47,稍后会解释它。

From the demo, it can be concluded that the Go is capable of preempting goroutines that are CPU-bound. But why is it possible because if a goroutines continuously taking up the CPU, how can it be preempted? This is a hard problem and there was a long discussion on the Go issue tracker. The problem was not addressed until Go 1.14, where asynchronous preemption was firstly introduced.

这个例子表明,Go 能抢占 CPU 密集型 goroutine。可是,如果它一直占用 CPU,调度器怎么得到执行机会去抢占它?这是个棘手的问题,在 Go 的问题跟踪系统里有过很长的讨论。直到 Go 1.14 首次引入异步抢占,才解决了这个问题。

In Go runtime, there is a daemon running on a dedicated thread M without a P, called sysmon (i.e. system monitor). When sysmon finds a goroutine that has been using P for more than 10ms (forcePreemptNS constant in Go runtime), it signals thread M by executing tgkill system call to forcefully preempt the running goroutine. Yes, you didn’t read that wrong. According to the Linux manual page, tgkill is used to send a signal to a thread, not to kill a thread. The signal is SIGURG, and the reason it being chosen is described here.

运行时有一个叫 sysmon(系统监控器)的后台任务,在专用线程 M 上运行,不需要 P。当它发现一个 goroutine 使用 P 已超过 10 毫秒(运行时常量 forcePreemptNS),就通过 tgkill 系统调用向执行它的线程发送信号,强制抢占当前 goroutine。没看错:根据 Linux 手册,tgkill 的用途是向指定线程发送信号,并非一定要终止线程。Go 选用 SIGURG 的原因见这里的说明。

Upon receiving SIGURG, the execution of the program is transferred to the signal handler, registered by a call of initsig function upon thread initialization. Note that the signal handler can run concurrently with goroutine code or the scheduler code, as depicted in the figure below. The execution switch from main program to signal handler is triggered by the kernel4,5.

收到 SIGURG 时,程序转而执行信号处理函数;运行时在线程初始化时通过 initsig 注册该函数。如下图所示,信号处理函数可以与 goroutine 代码或调度器代码并发运行。从主程序切换到信号处理函数的动作由内核触发4,5。

信号递送与信号处理函数的执行
Signal delivery and handler execution6
信号递送与信号处理函数的执行

In the signal handler, the program counter is set to the asyncPreempt function, allowing the goroutine to be suspended and creating space for preemption. In the assembly implementation of asyncPreempt function, it saves the goroutine’s registers and call asyncPreempt2 function at line 47. That is reason for the appearance of runtime.asyncPreempt:47 in the visualization. In asyncPreempt2, the goroutine g0 of thread M will enter gopreempt_m to disassociate goroutine G from M and enqueue G into the global run queue. The thread then continues with the schedule loop, finding another runnable goroutine and execute it.

信号处理函数将程序计数器设为 asyncPreempt 的入口,让 goroutine 可以暂停并接受抢占。asyncPreempt 的汇编实现先保存 goroutine 的寄存器,然后在第 47 行调用 asyncPreempt2。这就是跟踪图中出现 runtime.asyncPreempt:47 的原因。进入 asyncPreempt2 后,线程 M 的 g0 会执行 gopreempt_m,将 G 与 M 分离,并把 G 加入全局运行队列。线程接着回到调度循环,寻找并执行另一个可运行的 goroutine。

As preemption signal is triggered by sysmon but the actual preemption doesn’t happen until the thread receives preemption signal, this kind of preemption is asynchronous. That’s why goroutines can actually run beyond the time limit 10ms, like goroutine G9 in the example.

抢占信号由 sysmon 发出,但实际抢占要等到线程收到信号才发生,因此这种抢占是异步的。这也解释了为什么 goroutine 有时会运行超过 10 毫秒,示例中的 G9 就是如此。

GMP 模型中的非协作式抢占
Non-cooperative preemption in GMP model
GMP 模型中的非协作式抢占

Cooperative Preemption in Early Go早期 Go 的协作式抢占

In the early days of Go, Go runtime itself was not able to preempt a goroutines that have tight loop like the example above. We, as Go programmers, had to tell goroutines to cooperatively give up its processor P by making a call to runtime.Gosched() in the loop body. There was a Stackoverflow question that described an example and the behavior of runtime.Gosched().

早期 Go 的运行时无法自行抢占上例这种执行紧密循环的 goroutine。程序员需要在循环体内调用 runtime.Gosched(),让 goroutine 主动让出 P。Stack Overflow 上有一道相关问题,给出了示例并讨论了 runtime.Gosched() 的行为。

From the programmer’s point of view, this is very tedious and error-prone, and it did have some performance issue in actuality. Therefore, the Go team has decided to implement a clever way to preempt the goroutine by the runtime itself. This will be discussed in the next section.

对程序员来说,这既繁琐又容易出错,实际使用中也出现过性能问题。因此 Go 团队想了一个办法,让运行时自己安排抢占。下面来看看它怎么工作。

Cooperative Preemption Since Go 1.14Go 1.14 以来的协作式抢占

Do you wonder why I didn’t use fmt.Printf in each iteration and check the terminal to see whether both goroutines have chance to run? That’s because if I had done that, it would have become a cooperative preemption, not a non-cooperative preemption anymore.

你也许会问,为什么不在每轮迭代中调用 fmt.Printf,看终端输出就知道两个 goroutine 有没有机会运行?因为加上这条调用后,示例观察到的就可能变成协作式抢占,而非前面要看的非协作式抢占。

Disassemble the Program反汇编程序

To better understand this, let’s compile the program and analyze its assembly code. Since the Go compiler applies various optimizations that can make debugging more challenging, we need to disable them when building the program. This can be done by go build -gcflags="all=-N -l" -o fibonacci main.go.

为了理解其中原因,我们来编译程序并查看汇编。Go 编译器的许多优化会给调试增加困难,所以在构建时先关闭优化和内联:go build -gcflags="all=-N -l" -o fibonacci main.go。

For easier debugging, I use Delve, a powerful debugger for Go, to disassemble the fibonacci function: dlv exec ./fibonacci. Once inside the debugger, I run the following command to view the assembly code of the fibonacci function: disassemble -l main.fibonacci. You can find the assembly code of the original program here. As I’m building the program on my local machine, which is darwin/arm64, the assembly code built on your machine could be different from mine.

我使用 Go 调试器 Delve 反汇编 fibonacci 函数。先输入 dlv exec ./fibonacci,进入调试器后再执行 disassemble -l main.fibonacci。你也可以下载原程序的汇编代码。我的构建环境是 darwin/arm64,你在自己机器上得到的汇编可能不同。

That’s all set, let’s take a look at the assembly of the fibonacci function to see what it does.

准备就绪。来看看 fibonacci 的汇编到底做了什么。

      main.go:11      0x1023e8890     900b40f9        MOVD 16(R28), R16
      main.go:11      0x1023e8894     f1c300d1        SUB $48, RSP, R17
      main.go:11      0x1023e8898     3f0210eb        CMP R16, R17
      main.go:11      0x1023e889c     090c0054        BLS 96(PC)
      ...
      main.go:17      0x1023e8910     6078fd97        CALL runtime.convT64(SB)
      ...
      main.go:17      0x1023e895c     4d78fd97        CALL runtime.convT64(SB)
      ...
      main.go:20      0x1023e8a18     c0035fd6        RET
      main.go:11      0x1023e8a1c     e00700f9        MOVD R0, 8(RSP)
      main.go:11      0x1023e8a20     e3031eaa        MOVD R30, R3
      main.go:11      0x1023e8a24     dbe7fe97        CALL runtime.morestack_noctxt(SB)
      main.go:11      0x1023e8a28     e00740f9        MOVD 8(RSP), R0
      main.go:11      0x1023e8a2c     99ffff17        JMP main.fibonacci(SB)

MOVD 16(R28), R16 loads the value at offset 16 from the register R28, which holds the goroutine data structure g, and store that value in register R16. The loaded value is the stackguard0 field, which serves as the stack guard for the current goroutine. But what exactly is a stack guard? You may know that a goroutine’s stack is growable, but how does Go runtime determine when it needs to grow? The stack guard is a special value placed at the end of the stack. When the stack pointer reaches this value, Go runtime detects that the stack is nearly full and needs to grow—that’s exactly what the next three instructions do.

MOVD 16(R28), R16 从寄存器 R28 所指地址加 16 字节的位置读取一个值,将其存入 R16。R28 指向 goroutine 的 g 结构体,读到的字段是 stackguard0,即当前 goroutine 的栈保护边界。goroutine 的栈可以增长,运行时如何判断什么时候需要扩栈?它会在栈的边界设置一个保护值。当栈指针触及它,就表示栈空间快用完了。接下来的三条指令就是在做这个检查。

SUB $48, RSP, R17 loads the goroutine’s stack pointer from the register RPS to register R17 and subtracts 48 from it. CMP R16, R17 compares the stack guard with the stack pointer, and BLS 96(PC) branches to the instruction located 96 instructions ahead in the program if the stack pointer is less than or equal to the stack guard. Why less than or equal (≤) but not greater or equal (≥)? Because stack grows downward, the stack pointer is always greater than the stack guard.

SUB $48, RSP, R17 取栈指针寄存器 RSP 的值,减去 48 后写入 R17。CMP R16, R17 将栈保护边界与计算出的栈指针比较;如果栈指针小于或等于边界,BLS 96(PC) 就向前跳 96 条指令。为什么是小于等于,而不是大于等于?因为栈向低地址增长,正常情况下栈指针位于保护边界之上。

Have you ever wondered why these instructions don’t appear in the Go code but still show up in the assembly? That’s because upon compiling, Go compiler automatically inserts these instructions in function prologue. This applies for every function like fmt.Println, not just our fibonacci.

为什么我们没在 Go 源码里写这些指令,汇编中却有?因为编译器会把它们自动插在函数的序言里。这样的检查并非我们的 fibonacci 所独有,fmt.Println 等函数也有。

After advancing 96 instructions, execution reaches the MOVD R0, 8(RSP) instruction and then proceeds to CALL runtime.morestack_noctxt(SB). runtime.morestack_noctxt function will eventually call newstack to grow the stack and optionally enter gopreempt_m to trigger preemption as discussed in non-cooperative preemption. The key point of cooperative preemption is the condition for entering gopreempt_m, which is stackguard0 == stackPreempt. This means that whenever a goroutine wants to extend its stack, it will be preempted if its stackguard0 was set to stackPreempt earlier.

向前跳 96 条指令后,执行到 MOVD R0, 8(RSP),随后是 CALL runtime.morestack_noctxt(SB)。runtime.morestack_noctxt 最终调用 newstack 来处理扩栈,也可能进入 gopreempt_m 触发抢占,之后的过程与前面相同。协作式抢占的关键是进入 gopreempt_m 的条件:stackguard0 == stackPreempt。也就是说,当 goroutine 走到扩栈检查时,如果 stackguard0 已被设为 stackPreempt,就会触发抢占。

stackPreempt can be set by the sysmon if a goroutine has been running for more than 10ms. The goroutine will then be cooperatively preempted if it makes a function call or non-cooperatively preempted by the thread’s signal handler, whichever happens first. It can also be set when the goroutine enters or exits a system call or during the tracing phase of the garbage collector. See sysmon preemption, syscall entry/exit, garbage collector tracing.

如果 goroutine 持续运行超过 10 毫秒,sysmon 就可以设置 stackPreempt。之后,如果 goroutine 先发起函数调用,就可能以协作方式被抢占;如果线程的信号处理函数先得到执行,就会发生非协作式抢占。进入或退出系统调用时,以及垃圾收集器的追踪阶段,也可以设置这个值。可参见系统监控器发起抢占、进入系统调用、退出系统调用和垃圾收集器追踪的源码。

Trace Visualization查看执行跟踪

Alright, let’s rerun the program—make sure GOMAXPROCS=1 is set—and then check out the trace.

现在重新运行程序。记得设置 GOMAXPROCS=1,然后查看跟踪结果。

发生协作式抢占时的执行跟踪
Trace visualization when cooperative preemption happens
发生协作式抢占时的执行跟踪

You can clearly see that goroutines relinquish the logical processor after just tens of microseconds—unlike with non-cooperative preemption, where they might retain it for over 10 milliseconds. Notably, G9’s stack trace ends at the fmt.Printf inside the loop body, demonstrating the stack guard check in function prologue. This visualization precisely illustrates cooperative preemption, where goroutines voluntarily yield the processor.

图中可以看到,goroutine 只运行了几十微秒便让出逻辑处理器;相比之下,发生非协作式抢占之前,它可能占用处理器超过 10 毫秒。尤其值得注意的是,G9 的调用栈落在循环体中的 fmt.Printf,这展示了函数序言中的栈保护检查。在这里,goroutine 通过主动让出处理器实现了协作式抢占。

GMP 模型中的协作式抢占
Cooperative preemption in GMP model
GMP 模型中的协作式抢占

Handling System Calls系统调用的处理

System calls are services provided by the kernel that user-space applications access through an API. These services include fundamental operations, for example, reading files, establishing connections, or allocating memory. In Go, you rarely need to interact with system calls directly, as the standard library offers higher-level abstractions that simplify these tasks.

系统调用是内核通过 API 向用户态应用提供的服务,包括读文件、建立连接、分配内存等基础操作。在 Go 中很少需要直接发起系统调用,因为标准库提供了更高层的接口。

However, understanding how system calls work is crucial to gaining insight into Go runtime, standard library internals, as well as performance optimization. Go’s runtime employs an M:N threading model, further optimized by the use of logical processors P, making its approach to handling system calls particularly interesting.

不过,要理解 Go 运行时和标准库的内部实现,或是优化性能,就需要了解系统调用的工作方式。Go 在 M:N 线程模型上又引入了逻辑处理器 P,这使系统调用的处理过程格外值得一看。

System Call Classification系统调用的分类

In Go runtime, there are two wrapper functions around kernel system calls: RawSyscall and Syscall. The Go code we write uses these functions to invoke system calls. Each function accepts a system call number, its arguments, and returns values along with an error code.

Go 为内核系统调用提供了两个封装函数:RawSyscall 和 Syscall。我们写的 Go 代码可通过它们发起系统调用。两者都接收系统调用号和参数,并返回结果值与错误码。

Syscall is typically used for operations with unpredictable durations, such as reading from a file or writing an HTTP response. Since the duration of these operations is non-deterministic, Go runtime needs to account for them to ensure efficient use of resources. The function coordinates goroutines G, threads M, and processors P, allowing the Go runtime to maintain performance and responsiveness during blocking system calls.

Syscall 通常用于耗时难以预料的操作,例如读文件、写 HTTP 响应。由于无法预知何时完成,运行时必须把这些操作纳入调度。函数会协调 G、M 和 P,以便发生阻塞系统调用时仍能有效利用资源、保持程序的响应能力。

Nevertheless, not all system calls are unpredictable. For example, retrieving the process ID or getting the current time is usually quick and consistent. For these types of operations, RawSyscall is used. Since no scheduling is involved, the association between goroutines G, threads M, and processors P remains intact when raw system calls are made.

并非每个系统调用的耗时都难以预测。例如,获取进程 ID 或读取当前时间通常很快,耗时也比较稳定。这类操作可以用 RawSyscall。由于不涉及额外调度,发起原始系统调用时,G、M 和 P 的关联保持原样。

Internally, Syscall delegates to RawSyscall to perform the actual system call, but wraps it with additional scheduling logic, which will be described in detail in the next section.

Syscall 在内部委托 RawSyscall 执行实际系统调用,并在前后加上调度逻辑。下一节就看这层封装。

func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno) {
    runtime_entersyscall()
    r1, r2, err = RawSyscall6(trap, a1, a2, a3, 0, 0, 0)
    runtime_exitsyscall()
}

Scheduling in SyscallSyscall 中的调度

The scheduling logic is implemented in runtime_entersyscall function and runtime_exitsyscall function, respectively before and after actual system call is made. Under the hood, these functions are actually runtime.entersyscall and runtime.exitsyscall. This association are created at compile time.

runtime_entersyscall 和 runtime_exitsyscall 分别在实际系统调用之前和之后处理调度。它们在运行时里对应 runtime.entersyscall 和 runtime.exitsyscall,这些名字之间的关联在编译时建立。

Before an actual system call is made, Go runtime records that the invoking goroutine is no longer using the CPU. The goroutine G transitions from running state to syscall state, and its stack pointer, program counter, and frame pointer are saved for later restoration. The association between thread M and processor P is then temporarily detached, and P transitions to syscall state. This logic is implemented in the runtime.reentersyscall, which is invoked by runtime.entersyscall.

发起系统调用前,运行时记录调用方 goroutine 将不再执行 Go 代码。G 从 running 转入 syscall,栈指针、程序计数器和帧指针被保存,供之后恢复。接着,线程 M 暂时与处理器 P 分离,P 转入 syscall 状态。这些操作位于 runtime.reentersyscall,由 runtime.entersyscall 调用。

Interestingly, the sysmon (mentioned in the Non-cooperative Preemption section) monitors not only processors running goroutine code (where P is in running state), but also those making system calls (where P is in syscall state). If a P remains in syscall state for more than 10ms, instead of non-cooperatively preempting the running goroutine, a processor handoff takes place. This keeps the association between goroutine G and thread M, and attaches another thread M1 to this P, allowing runnable goroutines to run on that M1 thread. Apparently, as P is now executing code, its status is running rather than syscall as before.

非协作式抢占中见过的 sysmon 不只监控正在执行 goroutine 的处理器(running),也监控进入系统调用的处理器(syscall)。如果 P 在 syscall 状态停留超过 10 毫秒,发生的是处理器移交:G 仍与发起调用的 M 关联,但另一个线程 M1 可以接手这个 P,执行可运行的 goroutine。P 既然重新执行代码,状态也从 syscall 变成了 running。

Note that while system call is still in progress and whether sysmon happens to seize P or not, the association between goroutine G and thread M still remains. Why? Because the Go program (including Go runtime and Go code we write) are just user-space process. The only mean of execution that kernel provides user-space process is thread. It is the responsibility of thread to run Go runtime code, user Go code and make system call. A thread M makes system call on behalf of some goroutine G, that’s why the association between them is maintained as-is. Therefore, even if P is seized by sysmon, M remains blocked, waiting for the system call to complete before it can invoke the runtime.exitsyscall function.

只要系统调用还在进行,无论 sysmon 是否收回 P,G 和 M 都仍然关联。因为整个 Go 程序,包括运行时和用户代码,对内核来说都是用户态进程;内核为它提供的执行单位是线程。负责执行运行时代码、用户代码并发起系统调用的都是线程。M 正代 G 发起调用,所以二者的关联必须保留。即使 P 已被收回,M 也得继续等系统调用结束,随后才能执行 runtime.exitsyscall。

Another important point is that whenever a processor P is in syscall state, it can’t be taken up by another thread M to execute code until sysmon happens to seize it or until the system call is completed. Therefore, in case there are multiple system calls happening at the same time, the program (excluding system calls) doesn’t make any progress. That’s why Dgraph database hardcodes GOMAXPROCS to 128 to “allow more disk I/O calls to be scheduled”.

还有一点:只要 P 处于 syscall 状态,其他线程就不能直接取得它来执行代码;要等 sysmon 收回它,或者等系统调用结束。如果多个系统调用同时占住处理器,程序中系统调用以外的工作就可能停滞。这正是 Dgraph 数据库把 GOMAXPROCS 硬编码为 128 的原因,目的是“让更多磁盘 I/O 调用可以得到调度”。

As described in runtime.exitsyscall, there are two paths the scheduler can take after the syscall is finished: fast path and slow path. The latter only takes place if the former is not possible.

runtime.exitsyscall 的源码中有两条返回路径:快路径与慢路径。只有快路径走不通时,调度器才会转入慢路径。

The fast path occurs when if is a processor P available to execute the goroutine G that has just completed its system call. This P can either be the same one that previously executed G, if it is still in the syscall state (i.e., it hasn’t been seized by sysmon), or any other processor P1 currently in the idle state—whichever is found first. Note that when system call completes, the previous process P might not be in syscall state anymore bcause sysmon has seized it. Before the fast path exits, G transition from syscall state to running state.

如果刚结束系统调用的 G 能找到可用 P,就走快路径。可以是之前执行 G 的那个 P,前提是它仍处于 syscall 状态、还没被 sysmon 收回;也可以是另一个处于 idle 状态的 P1,取决于先找到哪一个。系统调用返回时,旧 P 可能已被 sysmon 收回,不再处于 syscall 状态。快路径结束前,G 会从 syscall 转回 running。

sysmon 未收回处理器 P 时的系统调用快路径
System call fast path when sysmon doesn’t seize processor P
sysmon 未收回处理器 P 时的系统调用快路径
sysmon 已收回处理器 P 时的系统调用快路径
System call fast path when sysmon seizes processor P
sysmon 已收回处理器 P 时的系统调用快路径

In the slow path, the scheduler tries retrieving any idle processor P once again. If it’s found, the goroutine G is scheduled to run on that P. Otherwise, G is enqueued into the global run queue and the associated thread M is stopped by stopm function, waiting to be woken up to continue the schedule loop.

走慢路径时,调度器会再尝试获取一次空闲 P。如果成功,就在该 P 上调度 G;否则,将 G 放入全局运行队列,并调用 stopm 停下关联的线程 M,等它被唤醒后再继续调度循环。

Network I/O and File I/O网络 I/O 与文件 I/O

This survey shows that 75% of Go uses cases are web services and 45% are static websites. It’s not a coincidence, Go is designed to be efficient for I/O operations to solve the notorious problem—C10K. To see how Go solves it, let’s take a look at how Go handles I/O operations under the hood.

一项调查显示,Go 的使用场景中,75% 涉及 Web 服务,45% 涉及静态网站。这并非巧合:Go 在设计时就注重 I/O 效率,意在应对著名的 C10K 问题。下面看看 Go 在底层怎样处理 I/O。

HTTP Server Under the HoodHTTP 服务器的底层实现

In Go, it’s incredibly straightforward to start an HTTP server. For example:

用 Go 启动一个 HTTP 服务器非常简单,例如下面这样。

package main

import "net/http"

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(200)
    })
	
    http.ListenAndServe(":80", nil)
}

Functions like http.ListenAndServe() and http.HandleFunc() might seem deceptively simple—but under the hood, they abstract away a lot of low-level networking complexity. Go relies on many fundamental socket operations (depicted in the figure below) to manage network communication.

http.ListenAndServe() 和 http.HandleFunc() 看起来简单,其实封装了大量底层网络操作。Go 依靠许多基础的 套接字 操作管理网络通信,下图给出了概览。

流式套接字使用的系统调用
Overview of system calls used with stream sockets7
流式套接字使用的系统调用

Specifically, http.ListenAndServe() leverages socket(), bind(), listen(), accept() system calls to create TCP sockets, which are essentially file descriptors. It binds the TCP listening socket to the specified address and port, listens for incoming connections, and creates a new connected socket to handle client requests. This is achieved without requiring you to write socket-handling code. Similarly, http.HandleFunc() registers your handler functions, abstracting away the lower-level details like using read() system call to read data, and write() system call to write data to the network socket.

具体来说,http.ListenAndServe() 借助 socket()、bind()、listen() 和 accept() 系统调用创建、绑定和监听 TCP 套接字,并接受新连接。套接字在进程中以文件描述符表示。监听套接字绑定到指定地址和端口;接受连接后,会得到新的已连接套接字,用来处理客户端请求。整个过程不需要你自己编写套接字管理代码。同样,http.HandleFunc() 注册你的处理函数,底层通过 read() 从网络套接字读取数据、通过 write() 写入数据等细节,都已由标准库封装。

Go 封装系统调用,为 HTTP 服务器提供简单的接口
Go abstracts system calls to provide simple interface for HTTP server
Go 封装系统调用,为 HTTP 服务器提供简单的接口

However, it’s not that simple for an HTTP server to handle tens of thousands of concurrent requests efficiently. Go employs several techniques to achieve this. Let’s take a closer look at some notable I/O models in Linux and how Go takes advantage of them.

可是,要让 HTTP 服务器高效地处理数以万计的并发请求,光靠简单的接口还不够。Go 为此结合了几种技术。先看看 Linux 上几种主要的 I/O 模型,以及 Go 如何利用它们。

Blocking I/O, Non-blocking I/O and I/O Multiplexing阻塞 I/O、非阻塞 I/O 与 I/O 多路复用

An I/O operation can be either blocking or non-blocking. When a thread issues a blocking system call, its execution is suspended until the system call completes with the requested data. In contrast, non-blocking I/O doesn’t suspend the thread; instead, it returns the requested data if available, or an error (EAGAIN or EWOULDBLOCK) if the data is not yet ready. Blocking I/O is simpler to implement but inefficient, as it requires the application to spawn N threads for N connections. In contrast, non-blocking I/O is more complex, but when implemented correctly, it enables significantly better resource utilization. See the figures below for a visual comparison of these two models.

I/O 操作有阻塞和非阻塞之分。线程发起阻塞系统调用后会暂停执行,直到请求的数据就绪、调用完成。非阻塞 I/O 则立即返回:数据已就绪就返回数据,尚未就绪则返回错误(EAGAIN 或 EWOULDBLOCK)。使用阻塞 I/O 的简单实现在 N 个连接上需要 N 个线程,易于编写但效率较低。非阻塞 I/O 更复杂,实现得当时却能显著提高资源利用率。下面两张图可对照阅读。

阻塞 I/O 模型
Blocking I/O model8
阻塞 I/O 模型
非阻塞 I/O 模型
Non-blocking I/O model9
非阻塞 I/O 模型

Another I/O model worth mentioning is I/O multiplexing, in which select, or poll system call is used to wait for one of a set of file descriptors to become ready to perform I/O. In this model, the application blocks on one of these system calls, rather than on the actual I/O system calls, such as recvfrom shown in the figures above. When select returns that the socket is readable, the application calls recvfrom to copy requested data to application buffer in user space.

还有一种模型叫 I/O 多路复用。应用调用 select 或 poll,等待一组文件描述符中的某一个就绪。此时阻塞发生在等待就绪的系统调用上,而不是上图中 recvfrom 这样的实际 I/O 操作上。等 select 报告套接字可读,应用才调用 recvfrom,将数据复制到用户空间的缓冲区。

I/O 多路复用模型
I/O multiplexing model10
I/O 多路复用模型

I/O Model in GoGo 的 I/O 模型

Go uses a combination of non-blocking I/O and I/O multiplexing to handle I/O operations efficiently. Due to the performance limitations of select and poll —as explained in this blog—Go avoids them in favor of more scalable alternatives: epoll on Linux, kqueue on Darwin, and IOCP on Windows. Go introduces netpoll, a function that abstracts these alternatives, to provide a unified interface for I/O multiplexing across different OS.

Go 将非阻塞 I/O 与 I/O 多路复用结合起来。由于 select 和 poll 存在性能限制(原因见这篇文章),Go 分别选择了更适合大规模并发的实现:Linux 的 epoll、Darwin 的 kqueue 和 Windows 的 IOCP。Go 用 netpoll 封装各平台的机制,对运行时提供统一的 I/O 多路复用接口。

How netpoll Worksnetpoll 的工作原理

Working with netpoll requires 4 steps: creating an epoll instance in kernel space, registering file descriptors with the epoll instance, epoll polls for I/O on file descriptors, and unregistering file descriptors from the epoll instance. Let’s see how Go implements these steps.

使用 netpoll 涉及四个步骤:在内核空间创建 epoll 实例、向 epoll 注册文件描述符、通过 epoll 轮询文件描述符的 I/O 事件、从 epoll 注销文件描述符。下面随 Go 的实现逐步来看。

Creating epoll Instance and Registering Goroutine创建 epoll 实例并登记 goroutine

When a TCP listener accepts a connection, accept4 system call is invoked with SOCK_NONBLOCK flag to set the socket’s file descriptor of the socket to non-blocking mode. Following this, several descriptors are created to integrate with Go runtime’s netpoll.

TCP 监听器接受连接时,会带着 SOCK_NONBLOCK 标志发起 accept4 系统调用,将新套接字的文件描述符设为非阻塞模式。随后会创建几种描述符,把它接入运行时的 netpoll。

  1. An instance of net.netFD is created to wrap the socket’s file descriptor. This struct provides a higher-level abstraction for performing network operations on the underlying kernel file descriptor. When an instance of net.netFD is initialized, epoll_create system call is invoked to create an epoll instance. The epoll instance is initialized in the poll_runtime_pollServerInit function, which is wrapped in a sync.Once to ensure it runs only once. Because of sync.Once, only a single epoll instance exists within a Go process and is used throughout the lifetime of the process.
    创建 net.netFD 实例来封装套接字的文件描述符。这个结构体在内核描述符之上提供了更高层的网络操作接口。初始化 net.netFD 时,通过 epoll_create 系统调用创建 epoll 实例。epoll 的初始化位于 poll_runtime_pollServerInit 中,外面用 sync.Once 保证只运行一次。正是因为有了 sync.Once,一个 Go 进程中才只有一个 epoll 实例,并在整个进程生命周期中共用它。
  2. Inside poll_runtime_pollOpen, Go runtime allocates a runtime.pollDesc instance, which contains scheduling metadata and references to the goroutines involved in I/O. The socket’s file descriptor is then registered with the interest list of epoll using epoll_ctl system call with EPOLL_CTL_ADD operation. As epoll monitors file descriptors rather than goroutines, epoll_ctl also associates the file descriptor with an instance of runtime.pollDesc, allowing the Go scheduler to identify which goroutine should be resumed when I/O readiness is reported.
    在 poll_runtime_pollOpen 中,运行时分配 runtime.pollDesc 实例,存放调度元数据和指向参与 I/O 的 goroutine 的引用。它以 EPOLL_CTL_ADD 操作调用 epoll_ctl,将套接字的文件描述符加入 epoll 的关注列表。由于 epoll 监控的是文件描述符,epoll_ctl 还会把该描述符与一个 runtime.pollDesc 实例关联起来。这样,当 I/O 就绪事件到达时,调度器就知道该恢复哪个 goroutine。
  3. An instance of poll.FD is created to manage read and write operations with polling support. It holds a reference to a runtime.pollDesc indirectly via poll.pollDesc, which is simply a wrapper.
    创建 poll.FD 实例,为读写操作提供轮询支持。它通过包装结构 poll.pollDesc 间接引用 runtime.pollDesc。

⚠️ Go does have problem with a single epoll instance as described in this open issue. There are discussions whether Go should use a single or multiple epoll instances, or even use another I/O multiplexing model like io_uring.

⚠️ Go 使用单个 epoll 实例也会遇到问题,见这条尚未关闭的 issue。其中有人讨论是否应该使用多个 epoll 实例,也有人提出改用 io_uring 等其他 I/O 模型。

Building on the success of this model for network I/O, Go also leverages epoll for file I/O. Once a file is opened, syscall.SetNonblock function is called to enable non-blocking mode for the file descriptor. Subsequently, poll.FD, poll.pollDesc and runtime.pollDesc instances are initialized to register the file descriptor with epoll’s interest list, allowing file I/O to be multiplexed as well.

网络 I/O 采用这一模型后,Go 也会将 epoll 用于文件 I/O。文件打开后,调用 syscall.SetNonblock 为文件描述符启用非阻塞模式,然后初始化 poll.FD、poll.pollDesc 和 runtime.pollDesc,将描述符注册到 epoll 的关注列表,使文件 I/O 也能多路复用。

The relationship between these descriptors is depicted in the figure below. Meanwhile net.netFD, os.File, poll.FD, and poll.pollDesc are implemented in user Go code (specifically in the Go standard library), runtime.pollDesc resides within Go runtime itself.

下图说明了这些描述符之间的关系。net.netFD、os.File、poll.FD 和 poll.pollDesc 在 Go 标准库中实现,runtime.pollDesc 则位于 Go 运行时内部。

Go 中各层描述符之间的关系
Relationship of descriptors in Go
Go 中各层描述符之间的关系

Polling File Descriptors轮询文件描述符

When a goroutine reads from socket or file, it eventually invokes the Read method of poll.FD. In this method, the goroutine makes read system call to get any available data from the file descriptor. If the I/O data is not ready yet, i.e. EAGAIN error is returned, Go runtime invokes poll_runtime_pollWait method to park the goroutine. The behavior is similar when a goroutine writes to a socket or file, with the main difference being that Read is replaced by Write, and the read system call is substituted with write. Now that the goroutine is in waiting state, it is the responsibility of netpoll to present goroutine to the Go runtime when the goroutine’s file descriptor is ready for I/O so that it can be resumed.

goroutine 从套接字或文件读取数据时,最终调用 poll.FD 的 Read 方法,然后执行 read 系统调用,读取描述符上可用的数据。如果 I/O 尚未就绪,调用返回 EAGAIN,运行时就通过 poll_runtime_pollWait 挂起该 goroutine。写入时过程类似,只是把 Read 换成 Write,把 read 系统调用换成 write。goroutine 此时处于 waiting 状态。等它所等待的描述符就绪,netpoll 有责任将它交还给运行时,使它能够恢复执行。

In Go runtime, netpoll is nothing more than a function having the same name. In netpoll function, epoll_wait system call is used to monitor up to 128 file descriptors in a specified amount of time. This system call returns the runtime.pollDesc instances that were previously registered (as described in the previous section) for each file descriptor that becomes ready. Finally, netpoll extracts the goroutine references from runtime.pollDesc and hands them off to the Go runtime.

在运行时中,netpoll 本身就是一个同名函数。netpoll 调用 epoll_wait,在指定时间内等待文件描述符就绪,一次最多返回 128 个事件。对于每个已就绪的描述符,系统调用都会带回前面注册的 runtime.pollDesc 实例。最后,netpoll 从 runtime.pollDesc 提取 goroutine 的引用,交给运行时。

But when is the netpoll function actually called? It’s triggered when a thread looks for a runnable goroutine to execute, as outlined in schedule loop. According to findRunnable function, netpoll is only consulted by the Go runtime if there are no goroutines available in either the local run queue of the current P or the global run queue. This means even if its file descriptor is ready for I/O, the goroutine is not necessarily woken up immediately.

什么时候调用 netpoll?如调度循环一节所述,线程寻找可运行的 goroutine 时就会调用它。按 findRunnable 的查找顺序,运行时先查当前 P 的本地队列和全局队列,找不到工作才查 netpoll。因此,即便某个 goroutine 等待的 I/O 已经就绪,它也未必会立即被唤醒。

As mentioned earlier, netpoll can block for a specified amount of time, and this is determined by the delay parameter. If delay is positive, it blocks for the specified number of nanoseconds. If delay is negative, it blocks until an I/O event becomes ready. Otherwise, when delay is zero, it returns immediately with any I/O events that are currently ready. In the findRunnable function, delay is passed with 0, which means that if one goroutine is waiting for I/O, another goroutine can be scheduled to run on the same kernel thread.

netpoll 等待多久由 delay 参数决定。正值表示最多等待指定的纳秒数;负值表示一直等到 I/O 事件就绪;零则表示立即返回当前已就绪的事件。findRunnable 中有一处传入的 delay 为 0,因此一个 goroutine 等待 I/O 时,同一个内核线程仍可调度另一个 goroutine。

Unregistering File Descriptors注销文件描述符

As mentioned above, epoll instance monitors up to 128 file descriptors. Therefore, it’s important to unregister file descriptors when they are no longer needed otherwise some goroutines may be starved. When file or network connection is no longer in used, we should close it by calling its Close method.

如前所述,epoll 轮询时每批最多处理 128 个就绪事件。描述符不用后应及时注销,以免其他等待的 goroutine 迟迟得不到处理。文件或网络连接不再使用时,应调用其 Close 方法关闭它。

Under the hood, the destroy method of poll.FD is called. This method eventually invokes the function poll_runtime_pollClose in Go runtime to make epoll_ctl with EPOLL_CTL_DEL operation. This unregisters the file descriptor from the epoll’s interest list.

底层会调用 poll.FD 的 destroy 方法,最终进入运行时的 poll_runtime_pollClose,通过 epoll_ctl 执行 EPOLL_CTL_DEL,将文件描述符从 epoll 的关注列表移除。

Putting It All Together串起整个轮询过程

The figure below illustrates the entire process of how netpoll works in Go runtime with file I/O. The process for network I/O is similar, but with the addition of a TCP listener that accepts connection and connection is closed. For simplicity purpose, other components in such as sysmon and other idle processors P are omitted.

下图以文件 I/O 为例,串起运行时中 netpoll 的完整流程。网络 I/O 与之类似,不过还要加上 TCP 监听器接受连接及关闭连接的环节。为了使图易读,省略了 sysmon 和其他空闲 P 等组件。

GMP 模型中 netpoll 的工作过程
How netpoll works in GMP model
GMP 模型中 netpoll 的工作过程

Garbage Collector垃圾收集器

You may know that Go includes a garbage collector (GC) to automatically reclaim memory from unused objects. However, as mentioned in the Program Bootstrap section, when the program starts, there are no threads initially available to run the GC. So where does the GC actually run?

Go 自带垃圾收集器(GC),能自动回收不再使用的对象所占的内存。但在程序启动一节的示意图里,起初没有线程专门留给 GC。那么 GC 在哪里运行?

Before we answer that question, let’s take a quick look at how garbage collection works. Go uses a tracing garbage collector, which identifies live and dead objects by traversing the allocated object graph starting from a set of root references. Objects that are reachable from the roots are considered live; those that are not are considered dead and eligible for reclamation.

先回顾垃圾收集的工作方式。Go 使用追踪式垃圾收集器,从一组根引用出发,遍历已分配对象构成的图。能从根到达的对象视为存活,其余对象则视为死亡,可以回收。

Go’s GC implements a tri-color marking algorithm with support for weak references. This design allows the garbage collector to run concurrently with the program, significantly reducing stop-the-world (STW) pauses and improving overall performance.

Go 的 GC 实现了三色标记算法,并支持弱引用。这种设计让垃圾收集器可以与程序并发运行,大幅缩短全局停顿(STW)时间,改善整体性能。

A Go garbage collection cycle can be divided into 4 stages:

一轮 Go 垃圾收集可以分为四个阶段。

  1. First STW: The process is paused so that all processors P can enter the safe point.
    第一次 STW:暂停程序,让所有处理器 P 都进入安全点。
  2. Marking phase: GC goroutines takes processor P shortly to mark reachable objects.
    标记阶段:GC 的 goroutine 占用 P 的一部分执行时间,标记可达对象。
  3. Second STW: The process is paused again to allow the GC to finalize the marking phase.
    第二次 STW:再次暂停程序,让 GC 完成标记阶段的收尾工作。
  4. Sweeping phase: Unpause the process and reclaim memory for unreachable objects in background.
    清扫阶段:程序恢复执行,后台回收不可达对象占用的内存。

Note that in step 2, garbage collection worker goroutine runs concurrently with regular goroutines on the same processor P. The findRunnable function (mentioned in Finding a Runnable Goroutine section) not only looks for regular goroutines but also for GC goroutines (step 1 and 2).

注意第二步。垃圾收集工作 goroutine 与常规 goroutine 并发,共用同一批 P。寻找可运行的 goroutine中介绍的 findRunnable 在寻找常规 goroutine 时,也会检查运行时自己的工作,包括 GC goroutine;可以对照前面列表开头的步骤。

Common Functions常用函数

Getting Goroutine: getg获取当前 goroutine:getg

In Go runtime, there is a common function that is used to retrieve the running goroutine in current kernel thread: getg(). Taking a glance at the source code, you can see no implementation for this function. That’s because upon compiling, the compiler rewrites calls to this function into instructions that fetch the goroutine from thread-local storage (TLS) or from registers.

Go 运行时经常用 getg() 获取当前内核线程上正在执行的 goroutine。看源码时会发现它只有声明,因为编译器会将调用改写为指令,直接从线程本地存储(TLS)或寄存器中取出 goroutine。

But when is the current goroutine stored in thread-local storage so it can be retrieved later? This happens during a goroutine context switch in the gogo function, which is called by execute. It also takes place when a signal handler is invoked, in the sigtrampgo function.

当前 goroutine 的信息是什么时候保存到线程本地存储的?一处是 goroutine 切换上下文时,由 execute 调用的 gogo 函数;另一处是触发信号处理时的 sigtrampgo 函数。

Goroutine Parking: gopark挂起 goroutine:gopark

This is a commonly used procedure in Go runtime for transitioning the current goroutine into a waiting state and scheduling another goroutine to run. The snippet below highlights some of its key aspects.

运行时经常通过这个过程将当前 goroutine 转入 waiting 状态,再调度另一个 goroutine。下面的片段列出了几个关键步骤。

func gopark(unlockf func(*g, unsafe.Pointer) bool, ...) {
    ...
    mp.waitunlockf = unlockf
    ...
    releasem(mp)
    ...
    mcall(park_m)
}

Inside releasem function, the goroutine’s stackguard0 is set to stackPreempt to trigger an eventual cooperative preemption. The control is then transferred to the g0 system goroutine, which belongs to the same thread currently running the goroutine, to invoke the park_m function.

在 releasem 中,运行时会将 goroutine 的 stackguard0 设为 stackPreempt,以便之后触发协作式抢占。随后控制权转到同一线程上的系统 goroutine g0,由它调用 park_m。

Inside park_m, the goroutine state is set to waiting and the association between the goroutine and thread M is dropped. Additionally, gopark receives an unlockf callback function, which is executed in park_m. If unlockf returns false, the parked goroutine is immediately made runnable again and rescheduled on the same thread M using execute. Otherwise, M enters the schedule loop to pick a goroutine and execute it.

在 park_m 中,goroutine 进入 waiting 状态,并与线程 M 解除关联。gopark 还接收一个名为 unlockf 的回调,由 park_m 执行。如果它返回 false,刚被挂起的 goroutine 会立即恢复为可运行,由 execute 在同一个 M 上重新调度;否则 M 进入调度循环,挑选下一个 goroutine。

Start Thread: startm启动线程:startm

This function is responsible for scheduling a thread M to run a given processor P. The diagram below illustrates the flow of this function, in which M1 thread is the parent of M2 thread.

这个函数负责调度线程 M,让它运行给定的处理器 P。下图展示了控制流,其中 M1 是创建 M2 的父线程。

startm 函数的执行流程
The startm function
startm 函数的执行流程

If P is nil, it attempts to retrieve an idle processor from the global idle list. If no idle processor is available, the function simply returns—indicating that the maximum number of active processors is already in use and no additional thread M can be created or reactivated. If an idle processor is found (or P was already provided), the function either creates a new thread M1 (if none is idle) or wakes up an existing idle one to run P.

如果传入的 P 为 nil,函数先尝试从全局空闲列表取出一个处理器。如果没有,就直接返回:所有可用处理器都已投入工作,无须再创建或唤醒线程。如果找到了空闲处理器,或调用方已经提供了 P,则优先唤醒已有的空闲线程来运行它;没有可用线程时才创建新线程 M1。

Once awakened, the existing thread M continues in the schedule loop. If a new thread is created, it’s done via the clone system call, with mstart as the entry point. The mstart function then transitions into the schedule loop, where it looks for a runnable goroutine to execute.

已有线程 M 醒来后,会继续执行调度循环。如需新建线程,则通过 clone 系统调用创建,以 mstart 为入口。mstart 随后进入调度循环,寻找可运行的 goroutine。

Stop Thread: stopm停止线程:stopm

This function adds thread M into the idle list and put it into sleep. stopm doesn’t return until M is woken up by another thread, typically when a new goroutine is created, as mentioned in Waking Up Processor section. This is achieved by futex system call, making M not eating CPU cycles while waiting.

这个函数把线程 M 放入空闲列表并使之睡眠。stopm 要等另一个线程唤醒 M 才会返回,典型场景是创建了新的 goroutine,见唤醒处理器。等待借助 futex 系统调用实现,因此 M 睡眠期间不消耗 CPU 周期。

Processor Handoff: handoffp移交处理器:handoffp

handoffp is responsible for transferring the ownership of a processor P from a thread Ms that is blocking in a system call to another thread M1. P will be associated with M1 to make progress by calling startm under certain conditions: if the global run queue is not empty, if its local run queue is not empty, if there is tracing work or garbage collection work to do, or if no thread is currently handling netpoll. If none of these conditions is met, P is returned to the processor idle list.

handoffp 负责把处理器 P 从阻塞在系统调用中的线程 M 移交给另一个线程 M1。在以下条件之一成立时,它通过 startm 将 P 关联到 M1,继续执行工作:全局运行队列非空、本地运行队列非空、有跟踪或垃圾收集工作待做,或者当前没有线程处理 netpoll。如果这些条件都不满足,P 就回到处理器空闲列表。

Go Runtime APIsGo 运行时 API

Go runtime provides several APIs to interact with the scheduler and goroutines. It also allows Go programmers to tune the scheduler and other components like garbage collector for their application specific needs.

Go 运行时提供了一些与调度器和 goroutine 交互的 API。开发者也可以按应用需要调整调度器、垃圾收集器等组件。

GOMAXPROCS用 GOMAXPROCS 控制并行度

This function sets the number of processors P in Go runtime, thus controlling the level of parallelism in a Go program. The default value of GOMAXPROCS is the value of runtime.NumCPU function, which queries the operating system CPU allocation for the Go process.

这个函数设置运行时的处理器 P 数量,决定 Go 程序的并行程度。在本文讨论的版本中,GOMAXPROCS 的默认值是 runtime.NumCPU 的返回值;后者向操作系统查询该 Go 进程可用的 CPU 数量。

GOMAXPROCS’s default value can be problematic, particularly in containerized environments, as described in this awesome post. There is an ongoing proposal to make GOMAXPROCS respect CPU cgroup quota limits, improving its behavior in such environments. In future versions of Go, GOMAXPROCS may become obsolete, as noted in the official documentation: “This call will go away when the scheduler improves.”

这篇文章讨论了 GOMAXPROCS 的默认值可能造成的问题,在容器环境中尤为明显。原文写作时已有提案,让 GOMAXPROCS 考虑 cgroup 的 CPU 配额,以改善容器中的行为。官方文档甚至提到,将来 GOMAXPROCS 或许会不再需要:“随着调度器改进,这个调用将会消失。”

Some I/O bound programs may benefit from a higher number of processors P than the default. For example, Dgraph database hardcodes GOMAXPROCS to 128 to allow more I/O operations to be scheduled.

某些 I/O 密集型程序可以受益于高于默认值的 P 数量。例如,Dgraph 数据库将 GOMAXPROCS 硬编码为 128,以便调度更多 I/O 操作。

Goexit用 Goexit 终止当前 goroutine

This function gracefully terminates the current goroutine. All deferred calls run before terminating the goroutine. The program continues execution of other goroutines. If all other goroutines exit, the program crashes. Goexit should be used testing rather than real-world application, where you want to abort the test case early (for example, if preconditions aren’t met), but you still want deferred cleanup to run.

这个函数会有序地终止当前 goroutine,终止前会执行所有 defer 调用。程序仍会继续执行其他 goroutine。如果其余 goroutine 也全部退出,程序会崩溃。作者建议将 Goexit 用在测试场景中:例如,前置条件不满足时,要提前中止测试用例,又希望已登记的清理操作照常运行。

Conclusion结语

The Go scheduler is a powerful and efficient system that enables lightweight concurrency through goroutines. In this blog, we explored its evolution—from the primitive model to the GMP architecture—and key components like goroutine creation, preemption, syscall handling, and netpoll integration.

Go 调度器让程序能够借助 goroutine 高效地实现轻量级并发。本文从早期调度器讲到 GMP 架构,走过了 goroutine 的创建、抢占、系统调用处理,以及 netpoll 如何与调度器协作。

I hope you find this knowledge useful for writing more efficient and reliable Go programs. If you have any concerns, feel free to leave a comment. If you really enjoyed my content, please consider Buy Me A Coffee ! 😄

希望这些内容能帮助你写出更高效、更可靠的 Go 程序。有疑问欢迎到原文留言。如果你喜欢这篇文章,也欢迎请我喝杯咖啡!😄

References参考文献


Edit page
Share this post:

Comments


Previous Post
Paxos的魔法学研究报告
Next Post
My Senior Engineer Interview Experiences|我的高级软件工程师面试经历