2026-10-21 14:11:30 +08:00
<!DOCTYPE html>
< html lang = "zh-CN" data-theme = "light" >
< head >
< meta charset = "utf-8" >
< meta name = "viewport" content = "width=device-width, initial-scale=1" >
< title > 第 2 章 GMP 调度器: Go 如何把十万个 goroutine 跑起来 · Go 八股知识库< / title >
< meta name = "description" content = "从 GM 为什么不够用讲到 G、M、P、schedt 四个结构体,串起 schedule 到 goexit 的调度循环,讲透 work stealing、系统调用 handoff、异步抢占与 11 个调度场景。" >
< link rel = "stylesheet" href = "assets/doc.css" >
< / head >
< body >
< header class = "topbar" >
< div class = "tb-in" >
< a class = "brand" href = "index.html" > < span class = "logo" > GO< / span > < div > Go 八股< small > 从运行时原理到面试表达< / small > < / div > < / a >
< div class = "crumbs" >
< a href = "index.html" > 总目录< / a > < span class = "sep" > /< / span > < b > 第 2 章< / b >
< / div >
< div class = "spacer" > < / div >
< button class = "btn" id = "tocToggle" > ☰ 导航< / button >
< button class = "btn" id = "themeBtn" title = "切换到深色主题" > 深色< / button >
< / div >
< / header >
< div class = "layout" id = "layout" >
< aside class = "sidebar" >
< h2 > 章节目录< / h2 >
< nav id = "chapters" > < a class = "toc-a" href = "01-goroutine.html" > < i class = "cn" > 1< / i > 从进程到 goroutine: 并发模型的底层账本< / a > < span class = "toc-a active" aria-current = "page" > < i class = "cn" > 2< / i > GMP 调度器: Go 如何把十万个 goroutine 跑起来< / span > < div class = "subnav current" > < a class = "toc-a lv3" href = "#sec-2-1" > 2.1 从 GM 到 GMP: 为什么需要 P< / a > < a class = "toc-a lv3" href = "#sec-2-2" > 2.2 三个结构体: G、M、P 与 schedt< / a > < a class = "toc-a lv3" href = "#sec-2-3" > 2.3 调度循环: schedule → findRunnable → execute → goexit< / a > < a class = "toc-a lv3" href = "#sec-2-4" > 2.4 本地队列与 work stealing< / a > < a class = "toc-a lv3" href = "#sec-2-5" > 2.5 系统调用: reentersyscall、handoff 与 exitsyscall< / a > < a class = "toc-a lv3" href = "#sec-2-6" > 2.6 阻塞与唤醒: park_m、ready 与 wakep< / a > < a class = "toc-a lv3" href = "#sec-2-7" > 2.7 抢占:从协作式到基于信号的异步抢占< / a > < a class = "toc-a lv3" href = "#sec-2-8" > 2.8 十一个调度场景串讲< / a > < a class = "toc-a lv3" href = "#sec-2-9" > 2.9 本地队列挂 P 还是 M, 为什么< / a > < a class = "toc-a lv3" href = "#sec-2-10" > 2.10 观测调度器: schedtrace 与 pprof< / a > < / div > < a class = "toc-a" href = "03-memory.html" > < i class = "cn" > 3< / i > 内存分配:从 mspan 到 mallocgc< / a > < a class = "toc-a" href = "04-gc-mark.html" > < i class = "cn" > 4< / i > 垃圾回收(上):三色标记与写屏障< / a > < a class = "toc-a" href = "05-gc-source.html" > < i class = "cn" > 5< / i > 垃圾回收(下):一次 GC 的完整生命周期< / a > < a class = "toc-a" href = "06-slice.html" > < i class = "cn" > 6< / i > slice: 视图、扩容与共享底层数组< / a > < a class = "toc-a" href = "07-map.html" > < i class = "cn" > 7< / i > map: 从 hmap/bmap 到 1.24 Swiss Table< / a > < a class = "toc-a" href = "08-channel.html" > < i class = "cn" > 8< / i > channel: CSP 的载体与并发编排< / a > < a class = "toc-a" href = "09-defer.html" > < i class = "cn" > 9< / i > defer、panic、recover 与闭包< / a > < a class = "toc-a" href = "10-sync.html" > < i class = "cn" > 10< / i > 锁与同步原语:从 Mutex 到 singleflight< / a > < a class = "toc-a" href = "11-context.html" > < i class = "cn" > 11< / i > context: 取消、超时与 goroutine 泄露防治< / a > < a class = "toc-a" href = "12-interface.html" > < i class = "cn" > 12< / i > 接口:隐式契约与运行时表示< / a > < a class = "toc-a" href = "13-puzzles.html" > < i class = "cn" > 13< / i > 并发编程题:从交替打印到 worker pool< / a > < a class = "toc-a" href = "14-interview.html" > < i class = "cn" > 14< / i > 面试速查:对比、版本演进与高频追问< / a > < / nav >
< div class = "side-foot" >
< a class = "btn" href = "index.html" > ← 总目录< / a >
< / div >
< / aside >
< div class = "mask" id = "mask" > < / div >
< main class = "main-col" >
< article >
< p class = "chapnav" >
< a href = "index.html" > Go 八股< / a >
< span > ·< / span >
< span > 第 < b class = "pos" > 2< / b > / 14 章< / span >
< / p >
< h2 id = "ch2" > < span class = "n" > 2< / span > GMP 调度器: Go 如何把十万个 goroutine 跑起来< / h2 >
2026-10-22 23:35:36 +08:00
< div class = "box ok" >
< span class = "bt" > 面试直答 · 30 秒版< / span >
2026-10-25 11:57:02 +08:00
< p > G 是任务与现场, M 是真正执行代码的内核线程, P 是「执行许可 + 本地资源」:本地队列、< code > mcache< / code > 、空闲栈缓存都挂在 P 上。一条硬规则是 < b > M 必须先拿到 P, 才能跑用户 G< / b > ,所以真正并行的用户代码数量受 P 的个数限制, P 的数量默认等于 < code > GOMAXPROCS< / code > 。好处是绝大多数调度决策在用户态、在 P 自己的队列上完成,基本不加锁;某个 P 没活了还能去别的 P 那里偷。G 阻塞在系统调用里时, M 带着它进内核, P 被交给别的 M 继续干活。< / p >
2026-10-22 23:35:36 +08:00
< ul >
2026-10-25 11:57:02 +08:00
< li > 顺序:先说三个角色,再说「为什么非得有 P」, 最后补一句 handoff。< / li >
< li > 本地队列满了溢出到全局队列,空了去别的 P 偷一半。< / li >
< li > 调度循环三步:找可运行的 G → 切过去执行 → 结束后再找下一个。< / li >
2026-10-22 23:35:36 +08:00
< / ul >
< / div >
2026-10-21 14:11:30 +08:00
< div class = "lead" >
2026-10-25 11:57:02 +08:00
< b > 这一章解决什么:< / b > 第 1 章把 goroutine 这笔账算清了——2 KB 起步的栈、几十纳秒的切换、三种阻塞各自卡住谁。
这一章把镜头推到 runtime 内部,只回答一个问题:< b > G 在 G、M、P 这三个对象之间怎么流动< / b > 。
路线是:先解释「为什么非要有 P」( 2.1) , 再把四个结构体摊开对照( 2.2) , 然后跟着调度循环走一圈( 2.3) ,
依次看清队列怎么偷( 2.4)、系统调用怎么把 P 交出去( 2.5) 、阻塞与唤醒怎么接上( 2.6)、跑飞的 G 怎么被拽回来( 2.7) ,
最后用 11 个场景串一遍( 2.8)、回答「队列挂 P 还是 M」( 2.9) 、再教你把它看见( 2.10)。
< / div >
< div class = "box tip" >
< span class = "bt" > 怎么读这一章< / span >
< ul >
< li > 本章配了 < b > 5 张示意图< / b > ,都在讲「谁把什么交给谁」。< b > 先看图,再读字< / b > ,图的顺序就是本章的主线。< / li >
< li > 标了 < span class = "tag s" > 可跳过< / span > 的段落是字段级、版本级细节,第一遍跳过不影响主线,第二遍再来补。< / li >
< li > G、M、P 的定义、< code > GOMAXPROCS< / code > 的默认值与容器坑在第 1 章 1.2 / 1.5 已经讲过,本章不重复,只在用到时给一句提示。< / li >
< / ul >
2026-10-21 14:11:30 +08:00
< / div >
< h3 id = "sec-2-1" > 2.1 从 GM 到 GMP: 为什么需要 P< / h3 >
2026-10-25 11:57:02 +08:00
< p > < span class = "tag" > 现象< / span > Go 1.1 之前,调度器只有 G 和 M: 所有可运行的 G 挤在< b > 一条全局队列< / b > 里,任何线程想跑 G 都得先加锁取一个。单核上这套逻辑毫无问题;核数一多,两个成本被同时放大——每次创建 G、每次 G 结束、每次 G 被唤醒,都要抢< b > 同一把全局锁< / b > ,核越多争得越凶;而 < code > mcache< / code > 、空闲栈缓存这些本该「本地化」的资源如果被所有 M 共享,也只能靠锁串行化。< / p >
< p > < span class = "tag" > 机制< / span > P 的引入, 是在「跑什么」( G) 和「谁来跑」( M) 之间插一层「< b > 凭什么跑< / b > 」。< code > runtime/HACKING.md< / code > 里有一句很准确的话: 调度器在匹配三样东西——G( code to execute) 、M( where to execute) 、P( rights and resources to execute) 。P 自己不执行任何代码,它是一份< b > 执行许可加本地资源包< / b > 的三合一:< / p >
< ul >
< li > < b > 许可< / b > : M 拿到 P 才有资格执行用户 G; 没有 P 的 M 只能跑调度代码或陷在系统调用里。< / li >
< li > < b > 本地队列< / b > :这个 P 的 < code > runq< / code > / < code > runnext< / code > ,取 G 基本不加锁( 2.4)。< / li >
< li > < b > 本地资源< / b > : < code > mcache< / code > 、空闲栈缓存, 小对象分配不用抢堆锁; GC 的标记工作也按 P 分摊。< / li >
< / ul >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 维度< / th > < th > GM( 无 P) < / th > < th > GMP( 有 P) < / th > < / tr > < / thead >
< tbody >
< tr > < td > 待运行 G 存在哪< / td > < td > 只有一条全局队列,所有 M 共享< / td > < td > 每个 P 一条本地队列,全局队列兜底< / td > < / tr >
< tr > < td > 取 G 的成本< / td > < td > 每次都要加全局锁< / td > < td > 本地队列、< code > runnext< / code > 、steal 都是 CAS< / td > < / tr >
< tr > < td > 内存分配< / td > < td > < code > mcache< / code > 争用< / td > < td > 每 P 一个 < code > mcache< / code > < / td > < / tr >
< tr > < td > 系统调用阻塞< / td > < td > M 抱着队列一起睡< / td > < td > P 可被 handoff 给别的 M< / td > < / tr >
< tr > < td > 并行度怎么控< / td > < td > 直接限制 M 的数量< / td > < td > 限制 P 的数量, M 可以多< / td > < / tr >
< / tbody >
< / table >
< / div >
< p > 换个说法: GM 模式下「< b > 有活要干< / b > 」和「< b > 有资格干< / b > 」是同一件事, 都绑在线程身上; GMP 把它们拆开, 线程只是执行器, 许可可以转手。这个拆分是后面所有机制( 偷活、handoff、抢占) 的地基。< / p >
< p > P 的数量等于 < code > GOMAXPROCS< / code > (默认值在当前版本怎么取、容器里踩过什么坑,第 1 章 < a href = "01-goroutine.html#sec-1-5" > 1.5< / a > 已经交代过),运行期还能改。这里只补一句这一章才用得上的:它限制的是< b > 同一时刻真正并行执行 Go 代码的 M 的数量< / b > ,不是线程总数——线程可以远多于 P, 多出来的 M 要么卡在系统调用里,要么在 < code > sched.midle< / code > 里睡觉。< / p >
< p > 空口说「P 决定并行度」不够,跑个数看看:固定 4 个纯 CPU 的 worker, 每个做 2 亿次取模累加,只改 < code > GOMAXPROCS< / code > 。< / p >
2026-10-21 14:11:30 +08:00
< pre data-lang = "go" data-name = "main.go: GOMAXPROCS 与真实并行度" > package main
import (
"fmt"
"runtime"
"sync"
"sync/atomic"
"time"
)
func work(n int) int64 {
var s int64
for i := 0; i < n; i++ {
s += int64(i % 7)
}
return s
}
func main() {
var sink int64
run := func(procs int) time.Duration {
runtime.GOMAXPROCS(procs)
var wg sync.WaitGroup
start := time.Now()
for w := 0; w < 4; w++ { // 固定 4 个 worker, 总工作量不变
wg.Add(1)
2026-10-25 11:57:02 +08:00
go func() { defer wg.Done(); atomic.AddInt64(& sink, work(200_000_000)) }()
2026-10-21 14:11:30 +08:00
}
wg.Wait()
return time.Since(start)
}
fmt.Println("NumCPU =", runtime.NumCPU())
d1 := run(1)
d4 := run(4)
fmt.Println("GOMAXPROCS=1:", d1.Round(time.Millisecond))
fmt.Println("GOMAXPROCS=4:", d4.Round(time.Millisecond))
fmt.Printf("speedup: %.2fx\n", float64(d1)/float64(d4))
}< / pre >
< pre data-lang = "text" data-name = "输出( Go 1.26.5 windows/amd64, NumCPU=20) " > NumCPU = 20
GOMAXPROCS=1: 574ms
GOMAXPROCS=4: 145ms
speedup: 3.95x< / pre >
2026-10-25 11:57:02 +08:00
< p > 只有一个 P 时,四个 worker 只能排队, 574 ms; 给四个 P 才真正并行, 145 ms, 接近 4 倍。再往上加 P 对这种负载没有意义——CPU 核就那么多,多出来的 P 只会在空闲链里排队。所以 P 的数量该对齐真实并行度:< b > 给少了排队,给多了空转< / b > ;真正要警惕的是另一种情况——< b > P 被占着却不干活< / b > 。< / p >
< p > < span class = "tag" > 代价< / span > 把许可和资源绑在一起是有代价的:< b > P 变成了稀缺品,任何「占着 P 空转」的行为都会被放大< / b > 。典型的有三种:纯 CPU 死循环(占满一个 P, 靠 2.7 的异步抢占兜底) 、阻塞在系统调用里却没能及时转手( 2.5 里的 handoff 慢半拍)、以及 < code > GOMAXPROCS=1< / code > 的环境里 GC 的 mark worker 拿不到额外的 P 并行标记。反过来说, P 开得比实际并行度多也没好处:多出来的 P 只会让自旋的 M 变多,白白烧 CPU。< / p >
< p class = "take" > < b > 一句话:< / b > GM 把「有活」和「有资格干」绑死在线程上; P 把这两件事拆开,于是许可可以转手、资源可以本地化,代价是 P 本身成了要抢的稀缺资源。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-2-2" > 2.2 三个结构体: G、M、P 与 schedt< / h3 >
2026-10-25 11:57:02 +08:00
< p > < span class = "tag" > 现象< / span > 「本地队列挂在 P 还是 M 上」「< code > g0< / code > 和普通 G 有什么区别」这类问题,背概念是答不出来的——只能去看字段挂在谁身上。所以这一节把四个结构体直接摊开,只留与调度有关的字段。< / p >
< p > < span class = "tag" > 机制< / span > 四个结构体都定义在 < code > runtime/runtime2.go< / code > 。先是 G: < / p >
2026-10-21 15:21:43 +08:00
< pre data-lang = "go" data-name = "runtime/runtime2.go( Go 1.25,节选)" > type g struct {
2026-10-25 11:57:02 +08:00
stack stack // 栈区间 [lo, hi)
stackguard0 uintptr // 栈溢出检查哨兵
m *m // 当前绑定的线程
sched gobuf // 换出时的 CPU 现场
2026-10-21 14:11:30 +08:00
atomicstatus atomic.Uint32 // _Grunnable / _Grunning / _Gwaiting ...
goid uint64
2026-10-25 11:57:02 +08:00
preempt bool // 抢占标记
startpc uintptr // 入口函数
2026-10-21 14:11:30 +08:00
}
type gobuf struct {
sp uintptr // 栈指针
pc uintptr // 下一条指令
g guintptr // 现场属于哪个 g
ctxt unsafe.Pointer
ret uintptr
lr uintptr
bp uintptr // 栈帧基址
}< / pre >
2026-10-25 11:57:02 +08:00
< p > < code > gobuf< / code > 就这么几个字段,这正是 goroutine 切换便宜的根源:换出时把 PC、SP、BP 存进 < code > g.sched< / code > ,换入时再搬回寄存器;不陷内核、不保存浮点与 SIMD 全套寄存器、不切页表。这笔账第 1 章 1.6 已经算过,这里只记住结论:< strong > 省下的是内核态往返和全套寄存器< / strong > 。< / p >
2026-10-21 14:11:30 +08:00
< p > G 的状态挂在 < code > atomicstatus< / code > 上,迁移关系是整个调度器的骨架:< / p >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 状态< / th > < th > 值< / th > < th > 含义< / th > < th > 常见去向< / th > < / tr > < / thead >
< tbody >
< tr > < td > < code > _Gidle< / code > < / td > < td > 0< / td > < td > 刚分配,还没初始化< / td > < td > → < code > _Grunnable< / code > < / td > < / tr >
< tr > < td > < code > _Grunnable< / code > < / td > < td > 1< / td > < td > 在队列里等 P< / td > < td > → < code > _Grunning< / code > < / td > < / tr >
< tr > < td > < code > _Grunning< / code > < / td > < td > 2< / td > < td > 正在某个 P 上执行< / td > < td > → < code > _Gsyscall< / code > 、< code > _Gwaiting< / code > 、< code > _Grunnable< / code > < / td > < / tr >
< tr > < td > < code > _Gsyscall< / code > < / td > < td > 3< / td > < td > 正在执行系统调用< / td > < td > → < code > _Grunning< / code > 或 < code > _Grunnable< / code > < / td > < / tr >
< tr > < td > < code > _Gwaiting< / code > < / td > < td > 4< / td > < td > 阻塞在 channel、mutex、timer 上< / td > < td > → < code > _Grunnable< / code > (被 < code > goready< / code > ) < / td > < / tr >
< tr > < td > < code > _Gdead< / code > < / td > < td > 6< / td > < td > 已退出,可被复用< / td > < td > 复用成 < code > _Grunnable< / code > < / td > < / tr >
< tr > < td > < code > _Gcopystack< / code > < / td > < td > 8< / td > < td > 正在扩大或收缩栈< / td > < td > → 回到原状态< / td > < / tr >
< tr > < td > < code > _Gpreempted< / code > < / td > < td > 9< / td > < td > 被抢占,停在安全点< / td > < td > → < code > _Grunnable< / code > < / td > < / tr >
< / tbody >
< / table >
< / div >
2026-10-25 11:57:02 +08:00
< p > 接着是 M。M 就是操作系统线程, 但它身上挂着三样不同的东西, 这三样分清了, 2.5 和 2.9 都不会再绕:< / p >
< figure class = "figure" >
< svg viewBox = "0 0 900 330" role = "img" aria-label = "一个 M 身上挂着三样东西:调度栈 g0、当前用户 goroutine curg、以及绑定的 P" >
< rect x = "28" y = "36" width = "252" height = "76" rx = "10" style = "fill:var(--card);stroke:var(--brand)" / >
< text x = "154" y = "62" text-anchor = "middle" font-size = "13.5" font-weight = "700" style = "fill:var(--brand)" > m.g0 · 调度栈< / text >
< text x = "154" y = "84" text-anchor = "middle" font-size = "11.5" style = "fill:var(--muted)" > 跑 schedule / findRunnable< / text >
< text x = "154" y = "102" text-anchor = "middle" font-size = "11.5" style = "fill:var(--muted)" > 线程自己的栈,不跑你的代码< / text >
< rect x = "28" y = "218" width = "252" height = "76" rx = "10" style = "fill:var(--card);stroke:var(--brand)" / >
< text x = "154" y = "244" text-anchor = "middle" font-size = "13.5" font-weight = "700" style = "fill:var(--brand)" > m.curg · 当前用户 G< / text >
< text x = "154" y = "266" text-anchor = "middle" font-size = "11.5" style = "fill:var(--muted)" > 你的函数跑在这里< / text >
< text x = "154" y = "284" text-anchor = "middle" font-size = "11.5" style = "fill:var(--muted)" > 换出时现场存进 g.sched< / text >
< rect x = "326" y = "124" width = "248" height = "80" rx = "10" style = "fill:var(--brand-soft);stroke:var(--brand)" / >
< text x = "450" y = "154" text-anchor = "middle" font-size = "14" font-weight = "700" style = "fill:var(--brand-ink)" > M · 一条操作系统线程< / text >
< text x = "450" y = "176" text-anchor = "middle" font-size = "11.5" style = "fill:var(--brand-ink)" > 真正被内核调度< / text >
< text x = "450" y = "194" text-anchor = "middle" font-size = "11.5" style = "fill:var(--brand-ink)" > 自己不带队列< / text >
< rect x = "620" y = "124" width = "252" height = "80" rx = "10" style = "fill:var(--card);stroke:var(--brand)" / >
< text x = "746" y = "152" text-anchor = "middle" font-size = "13.5" font-weight = "700" style = "fill:var(--brand)" > m.p · 绑定的 P< / text >
< text x = "746" y = "174" text-anchor = "middle" font-size = "11.5" style = "fill:var(--muted)" > runq / runnext / mcache< / text >
< text x = "746" y = "192" text-anchor = "middle" font-size = "11.5" style = "fill:var(--muted)" > 资源都在它身上< / text >
< g style = "stroke:var(--brand)" stroke-width = "1.4" fill = "none" >
< path d = "M326 148 L300 148 L300 74 L292 74" / >
< path d = "M326 180 L300 180 L300 256 L292 256" / >
< path d = "M574 164 L608 164" / >
< / g >
< g style = "fill:var(--brand)" >
< polygon points = "286,74 298,68 298,80" / >
< polygon points = "286,256 298,250 298,262" / >
< polygon points = "614,164 602,158 602,170" / >
< / g >
< text x = "300" y = "118" text-anchor = "middle" font-size = "11" style = "fill:var(--muted)" > 切换到用户代码< / text >
< text x = "450" y = "304" text-anchor = "middle" font-size = "12.5" style = "fill:var(--muted)" > 调度器代码在 g0 上跑,靠 gogo 切进 curg; curg 让出时靠 mcall 切回 g0< / text >
< / svg >
< p class = "figcap" > < b > 图 1 · 一个 M 身上挂着三样东西。< / b > 注意右边:队列和 < code > mcache< / code > 挂在 < b > P< / b > 上,不挂在 M 上——这就是 2.9 那道面试题的答案。< / p >
< / figure >
< p > < code > gogo< / code > 与 < code > mcall< / code > 是 < code > runtime/stubs.go< / code > 里声明、汇编实现的一对对偶:前者从 g0 栈切到用户 G 的栈,后者从用户 G 切回 g0。所以「调度器」从来不是某个常驻线程, 而是< b > 每条 M 在自己的 g0 栈上跑的一段循环< / b > 。< / p >
< p > 最后是 P 和全局的 < code > schedt< / code > : < / p >
2026-10-21 15:21:43 +08:00
< pre data-lang = "go" data-name = "runtime/runtime2.go( Go 1.25,节选)" > type p struct {
2026-10-21 14:11:30 +08:00
id int32
status uint32 // _Pidle / _Prunning / _Psyscall / _Pgcstop / _Pdead
m muintptr // 绑定的 M
mcache *mcache // 本地内存分配缓存
runqhead uint32
runqtail uint32
runq [256]guintptr // 环形本地队列
runnext guintptr // 下一个优先执行的 G
schedtick uint32 // 每执行一个 G 自增
syscalltick uint32
}
type schedt struct {
lock mutex
midle muintptr // 空闲 M 链
nmidle int32
pidle puintptr // 空闲 P 链
npidle atomic.Int32
runq gQueue // 全局队列
runqsize int32
nmspinning atomic.Int32 // 正在自旋找活的 M 数
maxmcount int32
}< / pre >
2026-10-25 11:57:02 +08:00
< p > P 的字段分三类:< b > 身份< / b > ( < code > id< / code > 、< code > status< / code > )、< b > 本地资源< / b > ( < code > mcache< / code > )、< b > 本地队列< / b > ( < code > runq< / code > /< code > runqhead< / code > /< code > runqtail< / code > /< code > runnext< / code > )。< code > schedt< / code > 则是全局后勤:< code > midle< / code > /< code > nmidle< / code > 管空闲 M, < code > pidle< / code > /< code > npidle< / code > 管空闲 P, < code > runq< / code > /< code > runqsize< / code > 兜底全局队列,< code > nmspinning< / code > 记「正在自旋找活的 M 有多少」——这个数字后面会在 2.4 和 2.6 反复出现。< / p >
2026-10-21 14:11:30 +08:00
< div class = "box note" >
< span class = "bt" > 为什么 G 一定要绑 P 才能跑< / span >
2026-10-25 11:57:02 +08:00
< p > 因为运行时把「能用什么」都挂在 P 上:从哪块 < code > mcache< / code > 分配对象、从哪条队列取 G、GC 的标记工作分给谁。没有 P 的 M 只能跑调度代码和系统调用,不能执行用户 G。这就是「P 是执行许可」的具体含义,也是为什么 < code > handoffp< / code > 一定要把 P 交给一个新 M, 而不是让 G 自己去找线程。< / p >
2026-10-21 14:11:30 +08:00
< / div >
2026-10-25 11:57:02 +08:00
< p > < span class = "tag" > 代价< / span > 结构体是< b > 版本敏感< / b > 的: 1.25 的 P 还有 < code > _Psyscall< / code > 状态,< b > 1.26 起这个状态已废弃< / b > (常量表里只剩 < code > _Psyscall_unused< / code > 占位) , P 在系统调用期间保持 < code > _Prunning< / code > ,判断「在不在系统调用」改成看 G 的状态与 < code > m.oldp< / code > 。所以面试被追问字段名时, 说清「P 上有队列和 mcache、M 上没有」比背具体值有用得多——前者十年不变,后者每年在变。< / p >
< p class = "take" > < b > 一句话:< / b > G 是任务加现场, M 是线程加两个栈, P 是许可加全部本地资源;判断「东西挂在谁身上」只看代码定义,不看名字像什么。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-2-3" > 2.3 调度循环: schedule → findRunnable → execute → goexit< / h3 >
2026-10-25 11:57:02 +08:00
< p > < span class = "tag" > 现象< / span > < code > schedtrace< / code > 里有个字段叫 < code > schedtick< / code > ,每执行完一个 G 就加 1。两个快照相减, 就知道这段时间调度了多少次——说明背后有个一直在转的循环。< b > 这个循环永不返回< / b > : 找不到活就去睡, 找到活就切过去, G 结束后再回来找下一个。< / p >
< p > < span class = "tag" > 机制< / span > 循环本体短到可以整段贴出来:< / p >
2026-10-21 15:21:43 +08:00
< pre data-lang = "go" data-name = "runtime/proc.go( Go 1.25,简化)" > func schedule() {
gp, inheritTime, tryWakeP := findRunnable() // 本地队列 → 全局队列 → netpoll → steal
if tryWakeP { // 拿到的不是普通 G, 叫醒一个 P 去跑
wakep()
}
execute(gp, inheritTime) // 不返回
2026-10-21 14:11:30 +08:00
}
func execute(gp *g, inheritTime bool) {
mp := getg().m
mp.curg = gp
gp.m = mp
casgstatus(gp, _Grunnable, _Grunning)
gp.preempt = false
gp.stackguard0 = gp.stack.lo + stackGuard
if !inheritTime {
mp.p.ptr().schedtick++
}
2026-10-21 15:21:43 +08:00
gogo(& gp.sched) // 汇编:恢复 sp/bp/g/ctxt, JMP 到上次停下的地方
2026-10-21 14:11:30 +08:00
}< / pre >
2026-10-25 11:57:02 +08:00
< p > < code > gogo< / code > 之后, CPU 已经在用户 G 的栈上执行,< code > schedule< / code > 那一帧还留在 g0 栈上,但< b > 没人会回来< / b > ——直到这个 G 让出或结束、通过 < code > mcall< / code > 切回 g0。所以这个「循环」其实是< b > 四条出口轮流把控制权送回 < code > schedule< / code > < / b > : < / p >
2026-10-21 14:11:30 +08:00
< ol class = "steps" >
2026-10-25 11:57:02 +08:00
< li > < strong > 正常结束< / strong > :函数返回 → < code > goexit1< / code > → < code > mcall(goexit0)< / code > ,状态 < code > _Gdead< / code > 、< code > gp.m = nil< / code > 、回 < code > schedule< / code > 。< / li >
< li > < strong > 被动阻塞< / strong > : channel、mutex 上等待 → < code > gopark< / code > → < code > mcall(park_m)< / code > ,状态变 < code > _Gwaiting< / code > 、< code > dropg< / code > 摘绑定、回 < code > schedule< / code > 。< / li >
< li > < strong > 主动让出< / strong > : < code > runtime.Gosched()< / code > → < code > mcall(gosched_m)< / code > → < code > goschedImpl< / code > ,状态回 < code > _Grunnable< / code > ,回 < code > schedule< / code > 。< / li >
2026-10-21 14:11:30 +08:00
< li > < strong > 被抢占< / strong > : < code > gopreempt_m< / code > → 同样走 < code > goschedImpl< / code > , 区别只在记账时标记为抢占( 2.7)。< / li >
< / ol >
2026-10-25 11:57:02 +08:00
< figure class = "figure" >
< svg viewBox = "0 0 900 350" role = "img" aria-label = "调度循环: schedule 找到 G, execute 切过去,四条出口再回到 schedule" >
< rect x = "300" y = "36" width = "300" height = "76" rx = "10" style = "fill:var(--brand-soft);stroke:var(--brand)" / >
< text x = "450" y = "66" text-anchor = "middle" font-size = "14" font-weight = "700" style = "fill:var(--brand-ink)" > schedule()< / text >
< text x = "450" y = "90" text-anchor = "middle" font-size = "11.5" style = "fill:var(--brand-ink)" > 活从哪来:本地 → 全局 → netpoll → 偷< / text >
< rect x = "300" y = "146" width = "300" height = "76" rx = "10" style = "fill:var(--card);stroke:var(--brand)" / >
< text x = "450" y = "176" text-anchor = "middle" font-size = "14" font-weight = "700" style = "fill:var(--brand)" > execute()< / text >
< text x = "450" y = "200" text-anchor = "middle" font-size = "11.5" style = "fill:var(--muted)" > casgstatus → gogo: 换栈, 不返回< / text >
< rect x = "300" y = "256" width = "300" height = "76" rx = "10" style = "fill:var(--card);stroke:var(--line)" / >
< text x = "450" y = "286" text-anchor = "middle" font-size = "13.5" font-weight = "700" style = "fill:var(--ink)" > 你的 G 在用户栈上跑< / text >
< text x = "450" y = "310" text-anchor = "middle" font-size = "11.5" style = "fill:var(--muted)" > goexit / gopark / Gosched / 抢占< / text >
< g style = "stroke:var(--brand)" stroke-width = "1.6" fill = "none" >
< path d = "M450 112 L450 140" / >
< path d = "M450 222 L450 250" / >
< path d = "M300 294 L150 294 L150 74 L292 74" / >
< / g >
< g style = "fill:var(--brand)" >
< polygon points = "450,144 444,132 456,132" / >
< polygon points = "450,254 444,242 456,242" / >
< polygon points = "298,74 286,68 286,80" / >
< / g >
< text x = "150" y = "184" text-anchor = "middle" font-size = "11.5" transform = "rotate(-90 150 184)" style = "fill:var(--muted)" > 四条出口都回到这里< / text >
< / svg >
< p class = "figcap" > < b > 图 2 · 调度器的循环。< / b > 和第 1 章图 3( G 的状态变化)角度不同:这张画的是< b > 线程< / b > 的路径——一条 M 一辈子就在这条环上转,每转一圈服务一个 G。< / p >
< / figure >
< p > 顺手解释一个容易被当成玄学的数字:< code > findRunnable< / code > 里只有 < code > _p_.schedtick % 61 == 0< / code > 时才去看一眼全局队列,而且这一次< strong > 只取一个 G< / strong > ( < code > globrunqget()< / code > ,不搬一批)。源码注释给的理由是公平性:否则两个互相唤醒的 goroutine 可以靠不断重生把本地队列占满,让其他 G 长时间等不到 P。「61 是质数、避免和 GC/timer 周期共振」是坊间说法,< b > 源码里没有这个解释< / b > ,别当结论背。真正「一次搬一批」的是另一条路径:本地队列空了以后调 < code > globrunqgetbatch(len(pp.runq)/2)< / code > ,取走全局队列的一半(上限 < code > sched.runqsize/gomaxprocs+1< / code > )。< / p >
2026-10-21 14:11:30 +08:00
< div class = "box warn" >
< span class = "bt" > 坑: Gosched 之后不是回本地队列< / span >
2026-10-25 11:57:02 +08:00
< p > < code > goschedImpl< / code > 里写的是 < code > globrunqput(gp)< / code > , G 进的是< strong > 全局< / strong > 队列,要等下一次 < code > schedtick % 61 == 0< / code > 的轮询、或者别的 P 来偷,才可能重新上 CPU。所以 < code > runtime.Gosched()< / code > 的语义是「我让出」,不是「我排到队首」——拿它当「让一下马上继续」会落空。< / p >
2026-10-21 14:11:30 +08:00
< / div >
2026-10-25 11:57:02 +08:00
< p > < span class = "tag" > 代价< / span > 这个设计换来的是「调度决策几乎不加锁」,代价是< b > 公平性只能靠轮询和偷活来凑< / b > :本地队列是无锁的,所以运行时没法精确知道全局有多少 G 在等; 61 次才看一次全局队列,意味着刚被 < code > Gosched< / code > 让出去的 G 可能等上几十次调度。这也解释了为什么「用 < code > Gosched< / code > 控制节奏」是个坏主意——它不是队列操作,只是放弃时间片。< / p >
< p class = "take" > < b > 一句话:< / b > 调度循环不是 while 而是四个入口共用一个出口:无论 G 是结束、阻塞、让出还是被抢,最终都回到 < code > schedule< / code > ,而 < code > schedule< / code > 永远在 g0 栈上。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-2-4" > 2.4 本地队列与 work stealing< / h3 >
2026-10-25 11:57:02 +08:00
< p > < span class = "tag" > 现象< / span > 一个 P 的本地队列最多放 256 个 G。放满了怎么办? 空了怎么办? < b > 两个方向都有明确答案,而且都不是「加把锁慢慢搬」< / b > ——这是 GMP 能撑住十万级 G 的真正原因。< / p >
< p > < span class = "tag" > 机制< / span > 每个 P 有一条容量 256 的环形队列 < code > p.runq< / code > ,外加只有一个格子的 < code > p.runnext< / code > 。< code > runnext< / code > 的语义是「下一个就跑它」:刚创建的 G、刚被唤醒的 G 放这里, 取的时候先看它( CAS 置空)。环形队列用 < code > runqhead< / code > 、< code > runqtail< / code > 两个游标,生产者改 tail、消费者改 head, 两侧用 < code > atomic.LoadAcq< / code > / < code > CasRel< / code > 保证可见性——< strong > 正常取 G 不加锁< / strong > 。< / p >
< p > 队列满了,< code > runqputslow< / code > 把本地队列< b > 一半< / b > 的 G 连同新来的这个打包塞进全局队列,全程< b > 只加一次锁< / b > ;队列空了,< code > findRunnable< / code > 按固定的五级顺序找活:< / p >
2026-10-21 14:11:30 +08:00
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 顺序< / th > < th > 位置< / th > < th > 加锁< / th > < th > 说明< / th > < / tr > < / thead >
< tbody >
< tr > < td > 1< / td > < td > < code > p.runnext< / code > < / td > < td > 无( CAS) < / td > < td > 上一个 G 留下的「下一个」,命中时继承时间片< / td > < / tr >
< tr > < td > 2< / td > < td > < code > p.runq< / code > 队头< / td > < td > 无( CAS head) < / td > < td > 常规路径,绝大多数在这里命中< / td > < / tr >
2026-10-21 15:21:43 +08:00
< tr > < td > 3< / td > < td > < code > sched.runq< / code > 全局队列< / td > < td > < code > sched.lock< / code > < / td > < td > 每 61 次调度强制查一次,只取 1 个;批量搬运另走 < code > globrunqgetbatch< / code > < / td > < / tr >
2026-10-21 14:11:30 +08:00
< tr > < td > 4< / td > < td > netpoll< / td > < td > 内部锁< / td > < td > 非阻塞查一次网络就绪的 G< / td > < / tr >
< tr > < td > 5< / td > < td > 别的 P 的队列尾部< / td > < td > 对方 CAS< / td > < td > work stealing, 偷一半, 最多 4 轮< / td > < / tr >
< / tbody >
< / table >
< / div >
2026-10-25 11:57:02 +08:00
< p > 偷活的细节值得单独看:< b > 偷的是尾部< / b > (最新的 G) , < b > 自己取的永远是队头< / b > (最老的 G) , 两边尽量不碰同一批对象, CAS 冲突最少。< code > runqgrab< / code > 里那句 < code > n := t - h; n -= n / 2< / code > 就是「偷一半、向上取整」。真正去偷之前, M 会先把自己标记成自旋(< code > sched.nmspinning< / code > ),自旋 M 的数量也有上限:不超过< b > 忙碌 P 数的一半< / b > (条件写的是 < code > 2*nmspinning < gomaxprocs - npidle< / code > ),多出来的直接睡下。< / p >
< figure class = "figure" >
< svg viewBox = "0 0 900 300" role = "img" aria-label = "P1 从 P0 的队尾偷走一半的 goroutine" >
< text x = "60" y = "66" font-size = "13.5" font-weight = "700" style = "fill:var(--brand)" > P0< / text >
< text x = "120" y = "66" font-size = "11.5" style = "fill:var(--muted)" > 6 个 G 在排队< / text >
< text x = "540" y = "66" font-size = "13.5" font-weight = "700" style = "fill:var(--brand)" > P1< / text >
< text x = "600" y = "66" font-size = "11.5" style = "fill:var(--muted)" > 本地队列空,自己取不到活< / text >
< g style = "fill:var(--brand-soft);stroke:var(--brand)" >
< rect x = "60" y = "96" width = "50" height = "34" rx = "6" / >
< rect x = "110" y = "96" width = "50" height = "34" rx = "6" / >
< rect x = "160" y = "96" width = "50" height = "34" rx = "6" / >
< rect x = "210" y = "96" width = "50" height = "34" rx = "6" / >
< rect x = "260" y = "96" width = "50" height = "34" rx = "6" / >
< rect x = "310" y = "96" width = "50" height = "34" rx = "6" / >
< / g >
< g font-size = "12" text-anchor = "middle" style = "fill:var(--brand-ink)" >
< text x = "85" y = "118" > G1< / text > < text x = "135" y = "118" > G2< / text > < text x = "185" y = "118" > G3< / text >
< text x = "235" y = "118" > G4< / text > < text x = "285" y = "118" > G5< / text > < text x = "335" y = "118" > G6< / text >
< / g >
< text x = "60" y = "152" font-size = "11.5" style = "fill:var(--muted)" > 队头(最老)< / text >
< text x = "360" y = "152" text-anchor = "end" font-size = "11.5" style = "fill:var(--muted)" > 队尾(最新)< / text >
< g style = "fill:var(--card);stroke:var(--line)" >
< rect x = "540" y = "96" width = "50" height = "34" rx = "6" / >
< rect x = "590" y = "96" width = "50" height = "34" rx = "6" / >
< rect x = "640" y = "96" width = "50" height = "34" rx = "6" stroke-dasharray = "4 4" / >
< rect x = "690" y = "96" width = "50" height = "34" rx = "6" stroke-dasharray = "4 4" / >
< rect x = "740" y = "96" width = "50" height = "34" rx = "6" stroke-dasharray = "4 4" / >
< / g >
< g font-size = "12" text-anchor = "middle" style = "fill:var(--muted)" >
< text x = "565" y = "118" > —< / text > < text x = "615" y = "118" > —< / text >
< / g >
< path d = "M540 78 L540 60 L370 60 L370 78" fill = "none" style = "stroke:var(--brand)" stroke-width = "1.6" stroke-dasharray = "6 4" / >
< polygon points = "370,88 364,76 376,76" style = "fill:var(--brand)" / >
< text x = "455" y = "50" text-anchor = "middle" font-size = "12" style = "fill:var(--brand)" > steal: 抢队尾的一半, 最多试 4 轮< / text >
< text x = "450" y = "196" text-anchor = "middle" font-size = "12.5" style = "fill:var(--muted)" > P0 的 6 个 G 被偷走 3 个,剩队头这 3 个继续由 P0 自己消费< / text >
< text x = "450" y = "224" text-anchor = "middle" font-size = "12.5" style = "fill:var(--muted)" > 偷尾部、取头部,两边永远不碰同一批对象 → 冲突少到可以只用 CAS< / text >
< text x = "450" y = "258" text-anchor = "middle" font-size = "12" style = "fill:var(--danger)" > 注意:自旋 M 数不超过忙碌 P 数的一半,否则多余线程直接睡下,不空转烧 CPU< / text >
< / svg >
< p class = "figcap" > < b > 图 3 · 偷活的方向。< / b > 被偷的是一段< b > 连续< / b > 的尾部区间,不是随机挑几个——这样一次 CAS 就能搬走一半。< / p >
< / figure >
< p > 本地队列的价值不只是「少加锁」,还有< b > 时间局部性< / b > :父 G 创建的子 G 进同一个 P, 父子往往共用同一片缓存和同一个 < code > mcache< / code > ,跑起来更快。这也是 Go 选择「创建时进本地、满了才溢到全局」的原因。< / p >
2026-10-21 14:11:30 +08:00
< div class = "box tip" >
< span class = "bt" > 面试怎么答: P 的本地队列空了怎么办< / span >
2026-10-25 11:57:02 +08:00
< p > 「先看 < code > runnext< / code > 和本地队列,再看全局队列(每 61 次调度强制看一次,只取 1 个),然后非阻塞查一次 netpoll 捞网络就绪的 G, 再 work stealing 从别的 P 尾部偷一半(最多 4 轮),还找不到就把 M 标成自旋再找一会儿,最后都没有就 < code > releasep< / code > 把 P 放回空闲链、< code > stopm< / code > 睡下。全程只有全局队列和 netpoll 要拿锁,本地队列和 steal 都是 CAS。」< / p >
2026-10-21 14:11:30 +08:00
< / div >
2026-10-25 11:57:02 +08:00
< p > < span class = "tag" > 代价< / span > 偷活不是免费的:偷一次要跨 P 搬一半 G, 被搬走的 G 在别处冷启动,< code > mcache< / code > 也跟着换;而且偷之前先自旋,自旋是纯烧 CPU。< b > 队列长度也不等于负载< / b > ——一个 P 排了 200 个 < code > time.Sleep(1ms)< / code > 的 G, 看起来积压严重, 实际几乎不耗 CPU。判断「调度器忙不忙」要看 < code > schedtick< / code > 的增速和 trace 里的调度延迟,不是看队列长度。< / p >
< p class = "take" > < b > 一句话:< / b > 本地队列负责「快」,全局队列负责「兜底」,偷活负责「不让 P 闲着」;三者靠 CAS + 一次加锁的溢出操作串起来,所以十万个 G 也不会把调度器压垮。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-2-5" > 2.5 系统调用: reentersyscall、handoff 与 exitsyscall< / h3 >
2026-10-25 11:57:02 +08:00
< p > < span class = "tag" > 现象< / span > 一个服务里加了几处「读配置文件、写日志文件」的同步 I/O, QPS 没变,但 < code > GODEBUG=schedtrace=1000< / code > 打出来的 < code > threads< / code > 一路涨、< code > idlethreads< / code > 不涨, P 却没闲着。< b > 线程在涨、P 在转< / b > ——这两个现象同时出现,基本就是这一节的主题:线程被系统调用吃掉了,而 P 在努力脱身。< / p >
2026-10-25 12:17:40 +08:00
< p > < span class = "tag" > 机制< / span > 这一节只回答三个问题:< b > 进内核时 P 怎么办、谁把 P 收走、回来以后 P 从哪来< / b > 。先看时间线,再一步一步展开。< / p >
< pre data-lang = "text" data-name = "一次阻塞系统调用的完整时间线" > 你的 G 调用 read(2)
│ ① 保存现场( pc / sp / bp → g.sched) , G 变成 _Gsyscall
│ P 仍记在 M 名下 —— 只是挂账,还没交权
▼
M 进内核。可能几微秒就回来, 也可能几秒钟不回来, Go 管不着
│ ② sysmon 在另一条线程上盯着,发现这个 M 迟迟不回来
│ 就把 P 收回,交给空闲的、或者新起的 M
▼
新 M 绑上这个 P, 立刻接着跑队列里的其他 G —— 队列跟着 P 走
│ ③ read 返回, G 变回 _Grunning
│ 拿得回原来的 P 就继续;拿不回就换一个空闲 P
▼
继续执行(最坏情况:回全局队列,等别的 P 来取)< / pre >
< h4 > 第一步:进内核 —— 只是挂账,还没交权< / h4 >
< p > < code > reentersyscall< / code > 只做两件事:把现场(< code > pc< / code > 、< code > sp< / code > 、< code > bp< / code > )存进 < code > g.sched< / code > ,再把 G 的状态从 < code > _Grunning< / code > 改成 < code > _Gsyscall< / code > 。< / p >
< p > < b > 它故意不交 P。< / b > 因为绝大多数系统调用几微秒就回来了, 一进一出就交接一次, 等于让所有快调用为罕见的慢调用付账。所以运行时先「挂个账」: P 还记在这个 M 名下,但旁边留个记号,好在之后判断「它是不是赖着不回来了」。< / p >
2026-10-25 11:57:02 +08:00
< div class = "box warn" >
2026-10-25 12:17:40 +08:00
< span class = "bt" > 可跳过 · 1.25 与 1.26 的差异< / span >
< p > < b > 1.25 及以前< / b > : 进内核前就解绑——P 状态置成 < code > _Psyscall< / code > , P 与 M 互相摘开,原 P 记进 < code > m.oldp< / code > 。< b > 1.26 起< / b > : 不再解绑, P 全程留在 M 名下、状态保持 < code > _Prunning< / code > ,只留 < code > m.oldp< / code > 和一份 < code > syscalltick< / code > 作凭据,等 sysmon 判定才交出去。结论不变:< b > 只是「交权」发生得更晚、更懒< / b > 。< / p >
2026-10-25 11:57:02 +08:00
< / div >
2026-10-25 12:17:40 +08:00
< h4 > 第二步: sysmon 把 P 收走< / h4 >
< p > < code > sysmon< / code > 是运行时起的一条后台线程,< b > 不绑 P< / b > ,所以它永远有空干活。空闲时每 20 µs 醒一次,越闲间隔越长,最长 10 ms。< / p >
< p > 醒来后它扫一遍所有 P: 如果某个 P 借给了一个陷在内核里的 M, 而< b > 这个 P 的队列里还有活< / b > ,或者< b > 系统里没有别的 M 能接手< / b > ,就当场把 P 收回来。< b > 只有队列空着、又确实有别的 M 闲着< / b > 时,它才宽限到 10 ms——反正抢过来也没人干活。< / p >
< div class = "box note" >
< span class = "bt" > 别把两个 10 ms 搞混< / span >
< p > 这里的 10 ms 是「宽限」:确认没人干活才等。另一个 10 ms( < code > forcePreemptNS< / code > )管的是完全不同的场景——一个 G 在 CPU 上连跑太久, 该被抢占了( 2.7)。< b > 一个是「线程会不会回来」, 一个是「goroutine 该不该让」< / b > ,这两句年年有人答串。< / p >
< / div >
< p > 收回来之后交给 < code > handoffp< / code > 决定去处,三选一:队列还有活 → 从空闲 M 里拿一个绑上,没有就新建线程;队列没活、但系统里没有自旋的 M → 把某个 M 标成自旋再绑,保证「总有人在找活」;还是没人要 → 把 P 放回空闲链,等谁需要谁来取。< / p >
2026-10-25 11:57:02 +08:00
< figure class = "figure" >
< svg viewBox = "0 0 900 310" role = "img" aria-label = "系统调用 handoff 时序: M 带着 G 进内核, P 被 sysmon 收回并交给另一个 M" >
< g font-size = "11.5" style = "fill:var(--muted)" >
< text x = "120" y = "34" > ① 进内核< / text >
< text x = "380" y = "34" > ② sysmon 判定( ≥1 个 tick) < / text >
< text x = "600" y = "34" > ③ 转手完成< / text >
< / g >
< g style = "stroke:var(--line)" stroke-dasharray = "4 5" >
< line x1 = "380" y1 = "44" x2 = "380" y2 = "274" / >
< line x1 = "600" y1 = "44" x2 = "600" y2 = "274" / >
< / g >
< text x = "16" y = "88" font-size = "12.5" font-weight = "700" style = "fill:var(--muted)" > M1< / text >
< rect x = "120" y = "64" width = "760" height = "52" rx = "8" style = "fill:var(--danger-bg);stroke:var(--danger-line)" / >
< text x = "500" y = "96" text-anchor = "middle" font-size = "12.5" style = "fill:var(--danger)" > M1 + G 卡在内核里 —— 内核负责调度, Go 运行时管不到,也不会回收这个线程< / text >
< text x = "16" y = "164" font-size = "12.5" font-weight = "700" style = "fill:var(--muted)" > P1< / text >
< rect x = "120" y = "140" width = "260" height = "52" rx = "8" style = "fill:var(--brand-soft);stroke:var(--brand)" / >
< text x = "250" y = "172" text-anchor = "middle" font-size = "12.5" style = "fill:var(--brand-ink)" > P1 借给了 M1< / text >
< rect x = "380" y = "140" width = "220" height = "52" rx = "8" style = "fill:var(--warn-bg);stroke:var(--warn-line)" / >
< text x = "490" y = "172" text-anchor = "middle" font-size = "12.5" style = "fill:var(--warn)" > 等 sysmon 来收< / text >
< rect x = "600" y = "140" width = "280" height = "52" rx = "8" style = "fill:var(--ok-bg);stroke:var(--ok-line)" / >
< text x = "740" y = "172" text-anchor = "middle" font-size = "12.5" style = "fill:var(--ok)" > 已经在 M2 手上干活< / text >
< text x = "16" y = "240" font-size = "12.5" font-weight = "700" style = "fill:var(--muted)" > M2< / text >
< rect x = "600" y = "216" width = "280" height = "52" rx = "8" style = "fill:var(--ok-bg);stroke:var(--ok-line)" / >
< text x = "740" y = "248" text-anchor = "middle" font-size = "12.5" style = "fill:var(--ok)" > 从 P1 的队列里接着取 G< / text >
< path d = "M490 192 L490 208 L600 208" fill = "none" style = "stroke:var(--ok)" stroke-width = "1.6" / >
< polygon points = "600,208 588,202 588,214" style = "fill:var(--ok)" / >
< text x = "500" y = "292" text-anchor = "middle" font-size = "11.5" style = "fill:var(--muted)" > 被转手的是 P( 许可 + 队列),不是 G —— G 还躺在内核里,等系统调用返回后自己找 P< / text >
< / svg >
< p class = "figcap" > < b > 图 4 · 系统调用的 handoff。< / b > 关键在于「转手的是 P」: 队列跟着 P 走,所以已经在排队的 G 一秒都不会多等。< / p >
< / figure >
2026-10-25 12:17:40 +08:00
< h4 > 第三步:回来以后 —— 能拿回原 P 就拿,拿不到就换< / h4 >
< p > 系统调用返回,< code > exitsyscall< / code > 先把 G 改回 < code > _Grunning< / code > ,然后按「能不能拿回 P」分三种情况: < / p >
2026-10-25 11:57:02 +08:00
< ol class = "steps" >
2026-10-25 12:17:40 +08:00
< li > < b > 原 P 还在等我< / b > :直接绑回去接着跑,这是绝大多数情况。< b > 判的不是「P 在不在空闲链里」< / b > ——P 从头到尾没进过空闲链;判的是 sysmon 有没有把它抢走。< / li >
< li > < b > 原 P 被抢走了,但还有别的空闲 P< / b > :换一个绑上,接着跑。< / li >
< li > < b > 一个空闲 P 都没有< / b > : G 改成可运行、放进< b > 全局队列< / b > ,这条线程自己去睡觉。< / li >
2026-10-25 11:57:02 +08:00
< / ol >
2026-10-25 12:17:40 +08:00
< p > 所以 G 永远不会丢:最坏也只是从「某个 P 的本地队列」挪到「全局队列」,等别的 P 来取。< / p >
< p > 还有一个分支值得知道:< code > entersyscallblock< / code > ,用于运行时< b > 明知< / b > 会堵很久的调用(比如某些文件操作)——它不等 sysmon 来收,< b > 当场交权< / b > 。反正早知道要堵,就不该占着 P。< / p >
2026-10-21 14:11:30 +08:00
< div class = "box danger" >
< span class = "bt" > 危险:阻塞式系统调用会推高线程数< / span >
2026-10-25 11:57:02 +08:00
< p > 每个卡在阻塞系统调用里的 G 都会占住一个 M: P 可以 handoff 出去, M 却不会被回收。大量读慢速文件、慢管道、同步磁盘 I/O 的服务,< code > schedtrace< / code > 里 < code > threads< / code > 会一路涨,< code > idlethreads< / code > 却跟不上。Go 只保证 P 不被浪费,< b > 不保证 M 不增长< / b > ——这类负载要么换成 netpoll 友好的非阻塞 I/O, 要么限制并发数。< / p >
2026-10-21 14:11:30 +08:00
< / div >
2026-10-25 12:17:40 +08:00
< p > < span class = "tag" > 代价< / span > 这一节的设计只为一条原则服务:< b > 保住稀缺的 P, 消耗可再生的 M< / b > 。新建一条线程才几十微秒,睡着的线程几乎零成本;而 P 稀缺,因为它身上绑着队列和 < code > mcache< / code > , 丢了就要有人干等。代价是线程数没人踩刹车: P 有上限, M 没有。所以看到 < code > threads< / code > 单向上涨,该调的是 I/O 模式(换非阻塞、限并发),而不是 < code > GOMAXPROCS< / code > 。< / p >
2026-10-25 11:57:02 +08:00
< p class = "take" > < b > 一句话:< / b > 系统调用不是「阻塞了一个 goroutine」, 而是「借走了一个线程」; 运行时的全部努力, 是把这个线程手里的 P 抢回来。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-2-6" > 2.6 阻塞与唤醒: park_m、ready 与 wakep< / h3 >
2026-10-25 11:57:02 +08:00
< p > < span class = "tag" > 现象< / span > 一个 < code > sync.Mutex< / code > 解锁后,等待它的 goroutine 常常「下一棒」就上了 CPU, 而不是排到 256 个 G 后面等。同样是被唤醒,为什么它这么快?< / p >
< p > < span class = "tag" > 机制< / span > 三个函数,各管一段:< / p >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 动作< / th > < th > 入口< / th > < th > 做了什么< / th > < th > G 最后在哪< / th > < / tr > < / thead >
< tbody >
< tr > < td > 阻塞< / td > < td > < code > gopark< / code > → < code > mcall(park_m)< / code > < / td > < td > 状态改 < code > _Gwaiting< / code > ,再 < code > dropg< / code > 摘掉与 M 的绑定,回 < code > schedule< / code > < / td > < td > 挂在等待队列上( channel 的 < code > waitq< / code > 、mutex 的 < code > sema< / code > ) , < b > 不在 < code > runq< / code > 里< / b > < / td > < / tr >
< tr > < td > 唤醒< / td > < td > < code > goready< / code > → < code > ready< / code > < / td > < td > 状态改回 < code > _Grunnable< / code > ,然后 < code > runqput< / code > 进< b > 唤醒者当前 P< / b > < / td > < td > < code > next = true< / code > 时进 < code > runnext< / code > ,否则进本地队尾< / td > < / tr >
< tr > < td > 补线程< / td > < td > < code > wakep< / code > → < code > startm< / code > < / td > < td > 发现还有空闲 P、却没有自旋 M 在找活< / td > < td > 不动 G, 只是叫醒或新建一个 M 去绑 P< / td > < / tr >
< / tbody >
< / table >
< / div >
< p > 表里有两处值得单独记。第一,< b > < code > gopark< / code > 的顺序是先改状态、再摘绑定< / b > ,反过来会让 GC 扫描时看到一个 < code > _Grunning< / code > 却已经没有 M 的 G。第二, < b > 唤醒时放回的是「唤醒者当前 P」的队列, 不是这个 G 原来待过的 P< / b > ; channel 收发、< code > Mutex.Unlock< / code > 、timer 到期都走这条路,所以解锁后等待者经常「下一棒」就上 CPU, 而不是排到 256 个 G 后面。< / p >
< p > < code > wakep< / code > 的触发条件只有两个数:< code > sched.npidle > 0< / code > (有闲着的 P) 且 < code > sched.nmspinning == 0< / code > (没人在自旋找活)。这两个数其实是一枚硬币的两面:< b > 自旋 M 是有线程没活,空闲 P 是有活没线程< / b > ,运行时靠它们决定这次该唤醒谁、还是该让谁睡。< / p >
< p > < span class = "tag" > 代价< / span > 「唤醒者把 G 放进自己的 < code > runnext< / code > 」是一个刻意的偏袒:它让唤醒延迟最小,但会让< b > 负载向热点 P 聚集< / b > ——一个全局锁被 T1 解锁,所有等待者都排进 P1 的队列,其他 P 反而在偷活。所以高并发下「锁 + 大量等待者」的场景,容易看到某个 P 的 < code > runqsize< / code > 明显偏高。这不是 bug, 是唤醒策略的副作用。< / p >
< p class = "take" > < b > 一句话:< / b > < code > gopark< / code > 把 G 摘下来交还给队列,< code > goready< / code > 把 G 插到唤醒者的下一个位置——一摘一插之间, M 从来没有被浪费。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-2-7" > 2.7 抢占:从协作式到基于信号的异步抢占< / h3 >
2026-10-25 11:57:02 +08:00
< p > < span class = "tag" > 现象< / span > 下面这段程序可以亲手验证抢占这件事:< code > GOMAXPROCS=1< / code > ,主 goroutine 跑一个< b > 函数体内没有任何调用< / b > 的四十亿次算术循环,另一个 goroutine 每 50 ms 打一次点。< / p >
2026-10-21 14:11:30 +08:00
< pre data-lang = "go" data-name = "main.go: 无函数调用的死循环里, 打点 goroutine 还能跑吗" > package main
import (
"fmt"
"runtime"
"sync/atomic"
"time"
)
func main() {
runtime.GOMAXPROCS(1)
var ticks, maxGap atomic.Int64
go func() {
last := time.Now()
for i := 0; i < 20; i++ {
time.Sleep(50 * time.Millisecond)
now := time.Now()
if gap := int64(now.Sub(last)); gap > maxGap.Load() {
maxGap.Store(gap)
}
last = now
ticks.Add(1)
}
}()
x := 0
for i := 0; i < 4_000_000_000; i++ { // 循环体里没有任何函数调用
x += i % 7
}
fmt.Printf("ticks=%d maxgap=%v sink=%d\n", ticks.Load(), time.Duration(maxGap.Load()), x& 1)
}< / pre >
< pre data-lang = "text" data-name = "输出( Go 1.26.5 windows/amd64, NumCPU=20) " > ticks=20 maxgap=63.2848ms sink=0
$ GODEBUG=asyncpreemptoff=1 go run main.go
ticks=0 maxgap=0s sink=0< / pre >
2026-10-25 11:57:02 +08:00
< p > 默认输出 < code > ticks=20< / code > :约 2.7 秒的纯算术循环期间,打点 goroutine 每 50 ms 都被准时唤醒一次。用 < code > GODEBUG=asyncpreemptoff=1< / code > 关掉异步抢占,同一份代码输出 < code > ticks=0< / code > ——打点的 G 被彻底饿死,直到主循环结束才拿到 CPU。< b > 这就是「死循环不再能独占 P」的直接证据< / b > ,也是 1.13 与 1.14 的分水岭。< / p >
< p > < span class = "tag" > 机制< / span > Go 1.13 及以前是< strong > 协作式抢占< / strong > :只在函数序言(< code > morestack< / code > 的栈检查)里检查 < code > gp.preempt< / code > 或 < code > stackguard0 == stackPreempt< / code > ,命中才让出。问题是 < code > for {}< / code > 里一个函数调用都没有,就永远没有检查点,一个死循环能把整个 P 焊死。< / p >
< figure class = "figure" >
< svg viewBox = "0 0 900 300" role = "img" aria-label = "异步抢占的五个步骤: sysmon 计时、置标记、发 SIGURG、改写 PC、回到队列" >
< text x = "450" y = "34" text-anchor = "middle" font-size = "12.5" style = "fill:var(--muted)" > 异步抢占( Go 1.14+):不需要代码配合,纯算术循环也能被打断< / text >
< g style = "fill:var(--brand-soft);stroke:var(--brand)" >
< rect x = "26" y = "96" width = "152" height = "70" rx = "8" / >
< rect x = "202" y = "96" width = "152" height = "70" rx = "8" / >
< rect x = "378" y = "96" width = "152" height = "70" rx = "8" / >
< rect x = "554" y = "96" width = "152" height = "70" rx = "8" / >
< rect x = "730" y = "96" width = "152" height = "70" rx = "8" / >
< / g >
< g font-size = "11.5" text-anchor = "middle" style = "fill:var(--brand-ink)" >
< text x = "102" y = "126" font-weight = "700" > sysmon 计时< / text >
< text x = "102" y = "148" > 同一个 G 跑了 10ms< / text >
< text x = "278" y = "126" font-weight = "700" > preemptone< / text >
< text x = "278" y = "148" > 置 preempt 标记< / text >
< text x = "454" y = "126" font-weight = "700" > 发 SIGURG< / text >
< text x = "454" y = "148" > 给对应的 M< / text >
< text x = "630" y = "126" font-weight = "700" > 改 PC< / text >
< text x = "630" y = "148" > 指向 asyncPreempt< / text >
< text x = "806" y = "126" font-weight = "700" > 回全局队列< / text >
< text x = "806" y = "148" > gopreempt_m< / text >
< / g >
< g style = "stroke:var(--brand)" stroke-width = "1.5" fill = "none" >
< path d = "M178 131 L196 131" / > < path d = "M354 131 L372 131" / >
< path d = "M530 131 L548 131" / > < path d = "M706 131 L724 131" / >
< / g >
< g style = "fill:var(--brand)" >
< polygon points = "200,131 190,126 190,136" / > < polygon points = "376,131 366,126 366,136" / >
< polygon points = "552,131 542,126 542,136" / > < polygon points = "728,131 718,126 718,136" / >
< / g >
< text x = "450" y = "212" text-anchor = "middle" font-size = "12.5" style = "fill:var(--muted)" > 选 SIGURG 是因为它默认被忽略、不干扰用户程序,而且系统调用返回时内核会检查它< / text >
< text x = "450" y = "244" text-anchor = "middle" font-size = "12.5" style = "fill:var(--danger)" > 协作式( 1.13-):只在函数入口检查 stackguard0 —— 循环里没有函数调用,就永远等不到检查点< / text >
< text x = "450" y = "272" text-anchor = "middle" font-size = "12.5" style = "fill:var(--ok)" > 异步式:信号 handler 把被中断处的 PC 改成 asyncPreempt, 等于「假装你刚调用过它」< / text >
< / svg >
< p class = "figcap" > < b > 图 5 · 抢占的五步。< / b > 第 4 步是整件事的关键:不是插入一条让出指令,而是< b > 改写上下文< / b > ,让返回时直接进入运行时。< / p >
< / figure >
< p > Go 1.14 起是< strong > 基于信号的异步抢占< / strong > : sysmon 发现某个 P 上的 G 连续跑了 10 ms, 就 < code > preemptone< / code > ——给 < code > gp.preempt< / code > 置位、把 < code > gp.stackguard0< / code > 改成 < code > stackPreempt< / code > ,再向对应 M 发一个 < code > SIGURG< / code > 。信号 handler 把被中断处的 PC 改到 < code > asyncPreempt< / code > ,由它保存现场、调 < code > asyncPreempt2< / code > → < code > gopreempt_m< / code > → < code > goschedImpl< / code > 。< / p >
2026-10-21 14:11:30 +08:00
< div class = "box note" >
2026-10-25 11:57:02 +08:00
< span class = "bt" > 版本差异:两种抢占并存< / span >
< p > Go 1.13 及以前只有协作式抢占,抢占点只在函数序言的栈检查里,< code > for {}< / code > 这类无调用循环真能把 P 饿死。Go 1.14 起默认开启基于 < code > SIGURG< / code > 的异步抢占,并引入 < code > _Gpreempted< / code > 状态;要复现旧行为用 < code > GODEBUG=asyncpreemptoff=1< / code > 。js/wasm 这类没有信号的环境仍然只有协作式抢占。< b > 两者不是替代关系,而是并在< / b > :能走到函数入口的走协作式(便宜),走不到的靠信号兜底。< / p >
2026-10-21 14:11:30 +08:00
< / div >
2026-10-25 11:57:02 +08:00
< p > < span class = "tag" > 代价< / span > 异步抢占的代价是< b > 安全点< / b > :不是随便哪条指令都能被打断,运行时只在编译器标记的异步安全点上真正接管(那些点上的寄存器状态是已知的)。所以一个极短的、位于安全点之间的计算块仍然可能延迟抢占——这叫「抢占延迟」,通常在几十微秒量级。另一个代价是 < code > SIGURG< / code > 与 cgo 的交互:跨 cgo 调用时信号线程的选择有额外约束,这也是 cgo 密集的程序偶尔看到调度抖动的原因之一。< / p >
< p class = "take" > < b > 一句话:< / b > 协作式靠 G 自己走到检查点,异步式靠信号从外部改写 PC; 前者便宜、后者兜底, 两者一起才让「一个死循环拖垮整个 P」成为历史。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-2-8" > 2.8 十一个调度场景串讲< / h3 >
2026-10-25 11:57:02 +08:00
< p > < span class = "tag" > 现象< / span > 前面七节各讲一个零件,合起来还是一团。这一节把它们拼成一次完整的行程:< b > 一个 G 从被创建,到跑起来,到停下来,最后回到队列< / b > 。< / p >
< p > < span class = "tag" > 机制< / span > 下表每一行只回答三个问题: 触发哪段代码、G 落在哪个队列、M 和 P 各归谁。建议< b > 横着读一行,竖着对一列< / b > ——竖着看「G 落在哪」,你会发现它一共只待过三个地方。< / p >
< h4 > 第一组: G 从哪来、排到哪< / h4 >
2026-10-21 14:11:30 +08:00
< div class = "tablewrap" >
< table >
< thead > < tr > < th > #< / th > < th > 场景< / th > < th > 调度器做了什么< / th > < th > G / M / P 归属< / th > < / tr > < / thead >
< tbody >
2026-10-25 11:57:02 +08:00
< tr > < td > 1< / td > < td > G1 用 < code > go< / code > 创建 G2< / td > < td > < code > newproc< / code > → < code > newproc1< / code > : G2 进当前 P 的 < code > runnext< / code > ,被挤掉的旧 runnext 落本地队尾< / td > < td > G2 归 P1 本地; M1 继续跑 G1< / td > < / tr >
2026-10-21 14:11:30 +08:00
< tr > < td > 2< / td > < td > G1 执行完返回< / td > < td > < code > goexit1< / code > → < code > mcall(goexit0)< / code > : G1 → < code > _Gdead< / code > 、< code > gp.m = nil< / code > , M1 回 g0 调 < code > schedule< / code > < / td > < td > M1 被复用; P1 不变< / td > < / tr >
< tr > < td > 3< / td > < td > 本地队列已满 256, 再创建 G< / td > < td > < code > runqputslow< / code > :本地约一半的 G 加新 G 打包进全局队列,加一次 < code > sched.lock< / code > < / td > < td > G 从 P1 本地溢出到全局队列< / td > < / tr >
< tr > < td > 4< / td > < td > 本地队列没满时创建 G< / td > < td > 只进本地队列,完全不碰全局队列< / td > < td > G 归 P1 本地< / td > < / tr >
< tr > < td > 5< / td > < td > 有 P 空闲、但没有自旋 M< / td > < td > 创建 G 后 < code > wakep< / code > : < code > startm< / code > 唤醒或新建 M, 绑上空闲 P< / td > < td > 新的 M2 + P2 组合开始干活< / td > < / tr >
2026-10-21 15:21:43 +08:00
< tr > < td > 6< / td > < td > 被唤醒的 M2 本地没活< / td > < td > < code > findRunnable< / code > 从全局队列批量取:请求本地队列长度的一半(< code > len(pp.runq)/2< / code > ),再被 < code > runqsize/GOMAXPROCS+1< / code > 截断< / td > < td > 一批 G 从全局搬到 P2 本地< / td > < / tr >
2026-10-21 14:11:30 +08:00
< tr > < td > 7< / td > < td > 全局队列也空< / td > < td > < code > stealWork< / code > :随机起点、最多 4 轮,从别的 P < strong > 尾部< / strong > 偷一半< / td > < td > G 从 P1 尾部搬到 P2< / td > < / tr >
2026-10-21 15:21:43 +08:00
< tr > < td > 8< / td > < td > 自旋 M 太多< / td > < td > 自旋 M 数上限约是忙碌 P 数的一半(< code > 2*nmspinning < gomaxprocs - npidle< / code > ),多余的 < code > stopm< / code > 进 < code > sched.midle< / code > < / td > < td > 多余 M 休眠, P 不变;有新活时再唤醒< / td > < / tr >
2026-10-25 11:57:02 +08:00
< / tbody >
< / table >
< / div >
< p > 这一组读下来只有一个结论:< b > 新 G 永远先进本地队列,本地队列是主路径,全局队列只是溢出的缓冲< / b > 。第 3 行和第 4 行的对比最能说明设计取向——满了才加锁,没满绝不加锁。< / p >
< h4 > 第二组: G 停下来之后< / h4 >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > #< / th > < th > 场景< / th > < th > 调度器做了什么< / th > < th > G / M / P 归属< / th > < / tr > < / thead >
< tbody >
2026-10-21 14:11:30 +08:00
< tr > < td > 9< / td > < td > G 阻塞在 channel 上< / td > < td > < code > gopark< / code > → < code > mcall(park_m)< / code > : < code > _Gwaiting< / code > 、< code > dropg< / code > 、< code > schedule< / code > ;对端 < code > goready< / code > 时 < code > ready< / code > 把它放进 < code > runnext< / code > < / td > < td > P 立刻转去执行别的 G, M 不浪费< / td > < / tr >
2026-10-25 11:57:02 +08:00
< tr > < td > 10< / td > < td > G 阻塞在系统调用< / td > < td > < code > reentersyscall< / code > 记下原 P( < b > 1.25 及以前< / b > 解绑并置 < code > _Psyscall< / code > ; < b > 1.26 起< / b > 不解绑、记 < code > m.oldp< / code > )→ sysmon 下一个 tick( 至少 20 µs) < code > retake< / code > → < code > handoffp< / code > 把 P 交给空闲或新建的 M< / td > < td > P 换主;原 M 带着 G 留在内核里< / td > < / tr >
2026-10-21 14:11:30 +08:00
< tr > < td > 11< / td > < td > G 跑太久被抢占< / td > < td > sysmon < code > preemptone< / code > ( 10 ms) → < code > SIGURG< / code > → < code > asyncPreempt< / code > → < code > gopreempt_m< / code > → < code > globrunqput< / code > < / td > < td > G 进< strong > 全局< / strong > 队列, P 换下一个 G< / td > < / tr >
< / tbody >
< / table >
< / div >
2026-10-25 11:57:02 +08:00
< p > 第二组的三行分别对应三种「不再占着 CPU」的方式: < b > 自己躺下等< / b > ( G 进等待队列, P 立刻释放)、< b > 被内核拖住< / b > ( P 被抢回来给别的 M) 、< b > 被强行叫停< / b > ( G 回全局队列,注意不是本地队列)。三者的共同点是:< b > P 都没有被浪费< / b > 。< / p >
< p > 这张表还有两个隐含结论。第一,< strong > 队列在 P 之间流动, G 不在 M 之间固定< / strong > :同一个 G 这次被 M1 跑,下次可能被 M3 跑,它绑定的只是「当前这个 P」。第二, < strong > 加锁只发生在碰全局队列的时候< / strong > :本地队列、< code > runnext< / code > 、steal 都是 CAS, 这才是 GMP 能撑住十万级 G 的关键。< / p >
2026-10-21 14:11:30 +08:00
< div class = "box note" >
< span class = "bt" > 数量关系别搞反: G 多不等于线程多< / span >
2026-10-25 11:57:02 +08:00
< p > 一个服务里有十万个 goroutine 很正常,但同一时刻能跑 Go 代码的只有 < code > GOMAXPROCS< / code > 个。其余 G 要么在某条队列里排队,要么阻塞在 channel/网络 I/O 上被 netpoll 管着。所以 < code > goroutines< / code > 数量大本身不是问题,< b > < code > runqueue< / code > 长期堆积、trace 里调度延迟变长< / b > 才是问题。< / p >
2026-10-21 14:11:30 +08:00
< / div >
< h3 id = "sec-2-9" > 2.9 本地队列挂 P 还是 M, 为什么< / h3 >
2026-10-25 11:57:02 +08:00
< p > < span class = "tag" > 现象< / span > 这是面试官验证「真看过源码还是背过八股」的一问。答案很硬:< strong > 挂在 P 上< / strong > 。< code > runq< / code > 、< code > runqhead< / code > 、< code > runqtail< / code > 、< code > runnext< / code > 全是 < code > p< / code > 的字段;< code > m< / code > 里只有一个 < code > p< / code > 指针,取 G 必须走 < code > m.p< / code > 。全局的那条才叫 < code > sched.runq< / code > 。< / p >
< p > < span class = "tag" > 机制< / span > 三条理由,按重要性排:< / p >
2026-10-21 14:11:30 +08:00
< ol class = "steps" >
2026-10-25 11:57:02 +08:00
< li > < strong > P 是调度上下文, M 只是执行器。< / strong > M 没有「待办队列」这个概念,它要么绑着 P( 能取 G) , 要么在系统调用里、要么在空闲链上( 取不了) 。队列挂在 P 上,「有队列」和「能跑」才是等价的。< / li >
< li > < strong > M 会阻塞、会被回收, P 不会。< / strong > M 陷在系统调用里时, P 被 handoff 给别的 M, 队列跟着 P 走,新 M 一绑上立刻有活干(图 4) 。队列若挂在 M 上, M 一阻塞就等于把待办列表拖走,必须跨线程搬运 G, 还得加锁。< / li >
< li > < strong > 队列和 < code > mcache< / code > 、空闲栈缓存一样,是 P 的本地资源。< / strong > 它们共享同一个前提:同一时刻只有一个 M 访问,所以不需要锁。挂在 M 上反而破坏这个前提——M 可以在 P 之间漂移、可以被不同 G 复用。< / li >
2026-10-21 14:11:30 +08:00
< / ol >
2026-10-25 11:57:02 +08:00
< p > 反过来问「为什么不挂 M」更清楚: M 阻塞在系统调用时队列没人消费,得专门有人把 G 抢出来;线程数不受 < code > GOMAXPROCS< / code > 约束, 队列数会随线程一起涨, steal 要遍历所有 M; 而且线程何时被内核调度, Go 说了不算——把待办列表绑在一个自己控制不了的对象上,调度器就没法保证公平与并行度。< / p >
2026-10-21 14:11:30 +08:00
< div class = "box tip" >
< span class = "bt" > 一句话话术< / span >
2026-10-25 11:57:02 +08:00
< p > 「本地队列挂在 P 上。P 是执行许可加本地资源的载体, M 只是执行者; M 阻塞时 P 能被 handoff 给别的 M, 队列跟着 P 走,所以线程阻塞不会让待办队列停摆。挂 M 的话, 线程一阻塞队列就被拖走, steal 还得跨线程加锁。」面试官要是继续追问 < code > runnext< / code > ,就答「它是 P 里单独的一个格子,专门给下一个要跑的 G 插队用」。< / p >
2026-10-21 14:11:30 +08:00
< / div >
< h3 id = "sec-2-10" > 2.10 观测调度器: schedtrace 与 pprof< / h3 >
2026-10-25 11:57:02 +08:00
< p > < span class = "tag" > 现象< / span > 机制讲完得能看见它。< code > GODEBUG=schedtrace=N< / code > 每 N 毫秒打一行调度器快照,加 < code > scheddetail=1< / code > 还会打印每个 P 和 M 的细节。下面这个程序把 < code > GOMAXPROCS< / code > 压到 1, 起 7 个忙等的 goroutine: 1 个占着 < code > runnext< / code > ,其余 6 个排在本地队列里,离 256 的容量还远。< / p >
2026-10-21 14:11:30 +08:00
< pre data-lang = "go" data-name = "main.go: 一个 P、七个忙等 G" > package main
import (
"fmt"
"runtime"
"time"
)
func main() {
runtime.GOMAXPROCS(1)
start := time.Now()
for i := 0; i < 7; i++ {
go func() {
for time.Since(start) < 600*time.Millisecond {
} // 忙等,不主动让出
}()
}
time.Sleep(700 * time.Millisecond)
fmt.Println("done", time.Since(start).Round(time.Millisecond))
}< / pre >
< pre data-lang = "bash" data-name = "观察调度器" > GODEBUG=schedtrace=200,scheddetail=1 go run main.go< / pre >
< pre data-lang = "text" data-name = "输出( Go 1.26.5 windows/amd64, NumCPU=20) " > SCHED 0ms: gomaxprocs=1 idleprocs=0 threads=6 spinningthreads=0 needspinning=1 idlethreads=3 runqueue=0 gcwaiting=false nmidlelocked=0 stopwait=0 sysmonwait=false
P0: status=1 schedtick=3 syscalltick=17 m=0 runqsize=6 gfreecnt=0 timerslen=1
...
SCHED 620ms: gomaxprocs=1 idleprocs=1 threads=6 spinningthreads=0 needspinning=0 idlethreads=3 runqueue=0 gcwaiting=false nmidlelocked=0 stopwait=0 sysmonwait=false
P0: status=0 schedtick=38 syscalltick=17 m=nil runqsize=0 gfreecnt=7 timerslen=1< / pre >
2026-10-25 11:57:02 +08:00
< p > < span class = "tag" > 机制< / span > 第一行说明:< code > runqueue=0< / code > 是全局队列长度( 0 个),< code > P0: status=1< / code > 是 < code > _Prunning< / code > ( < code > _Pidle< / code > 是 0) , < code > m=0< / code > 是绑定的 M 编号,< code > runqsize=6< / code > 说明 6 个 G 在 P0 本地排队,< code > schedtick< / code > 每执行一个 G 自增一次。最后一行的画面正好相反:活干完了,< code > idleprocs=1< / code > 、< code > status=0< / code > 、< code > m=nil< / code > 、< code > runqsize=0< / code > , P 被释放回空闲链、M 解绑, 7 个退出的 G 挂在 < code > gfreecnt< / code > ( < code > gFree< / code > )里等着复用——< b > 一张快照同时看到 < code > releasep< / code > 、< code > stopm< / code > 、G 复用三件事< / b > 。< / p >
< p > 不加 < code > scheddetail< / code > 时, SCHED 行尾会多一段方括号列表,每个 P 一个数字,比如 < code > runqueue=0 [ 6 ]< / code > 表示全局队列 0 个、唯一的 P 本地排队 6 个。常用字段对照:< / p >
2026-10-21 14:11:30 +08:00
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 字段< / th > < th > 含义< / th > < / tr > < / thead >
< tbody >
< tr > < td > < code > gomaxprocs< / code > < / td > < td > P 的数量,即当前 < code > GOMAXPROCS< / code > 的值< / td > < / tr >
< tr > < td > < code > idleprocs< / code > < / td > < td > 空闲 P 数(< code > sched.npidle< / code > ) < / td > < / tr >
< tr > < td > < code > threads< / code > < / td > < td > M 总数,含卡在系统调用里和空闲睡觉的< / td > < / tr >
< tr > < td > < code > spinningthreads< / code > < / td > < td > 正在自旋找活的 M 数(< code > sched.nmspinning< / code > ) < / td > < / tr >
< tr > < td > < code > idlethreads< / code > < / td > < td > 空闲 M 数(< code > sched.nmidle< / code > ) < / td > < / tr >
< tr > < td > < code > runqueue< / code > < / td > < td > 全局队列长度(< code > sched.runqsize< / code > ) < / td > < / tr >
< tr > < td > < code > [ ... ]< / code > < / td > < td > 每个 P 本地队列长度, P 有几个就有几个数字< / td > < / tr >
< tr > < td > < code > P0: status / m / runqsize< / code > < / td > < td > 该 P 的状态、绑定的 M 编号、本地队列长度< / td > < / tr >
< / tbody >
< / table >
< / div >
< p > 想看「G 等了多久才上 CPU」, 就要 pprof 和 trace 了:< / p >
< pre data-lang = "bash" data-name = "用 pprof 与 trace 看调度" > go tool pprof -http=:8080 http://127.0.0.1:6060/debug/pprof/goroutine
go tool pprof -http=:8080 http://127.0.0.1:6060/debug/pprof/threadcreate
go tool trace trace.out # trace 由 runtime/trace 采集< / pre >
2026-10-25 11:57:02 +08:00
< p > goroutine 视角回答「现在有多少 G、卡在哪个调用」; trace 里的 Scheduler latency profile 回答「G 从 < code > _Grunnable< / code > 到 < code > _Grunning< / code > 等了多久」,< b > 这才是 P 不够、自旋 M 不够的量化证据< / b > 。顺带一个对照: 2.1 那个实验把 < code > GOMAXPROCS< / code > 从 1 调到 4, 同样四个 worker 从 574 ms 降到 145 ms。< / p >
2026-10-21 14:11:30 +08:00
< div class = "box warn" >
2026-10-25 11:57:02 +08:00
< span class = "bt" > 注意: schedtrace 本身有开销< / span >
< p > 每打一行都要锁 < code > sched.lock< / code > 、遍历 < code > allp< / code > 、读每个 P 的状态,间隔调到 1 ms 会让吞吐明显下降。它适合排查时短时打开(配合 < code > scheddetail=1< / code > 看清每个 P) , 不要长期挂在线上。< / p >
< / div >
< p class = "take" > < b > 一句话:< / b > < code > schedtrace< / code > 看「谁在排队、谁在睡觉」, trace 看「G 等了多久」;前者适合判断结构是否失衡,后者适合证明延迟确实来自调度。< / p >
< h2 id = "ch2-sum" > 全章回顾:把五个角色和五个数字串起来< / h2 >
< div class = "box case" >
< span class = "bt" > 一张图记住这一章< / span >
< ul >
< li > < b > 五个角色< / b > : G = 任务 + 现场; M = 线程 + 两个栈( g0 与 curg) ; P = 许可 + 全部本地资源;< code > schedt< / code > = 全局后勤(空闲 M/P 链、全局队列);< code > sysmon< / code > = 不绑 P 的后台监工。< / li >
< li > < b > 一条硬规则< / b > : M 必须先拿到 P, 才能跑用户 G。所有「为什么挂在这不挂在那」的问题, 最后都归到这一条。< / li >
< li > < b > 一个循环< / b > : < code > schedule< / code > → < code > findRunnable< / code > → < code > execute< / code > → < code > gogo< / code > ,四条出口(结束/阻塞/让出/抢占)都回到 < code > schedule< / code > ,而它永远在 g0 栈上(图 2) 。< / li >
< li > < b > 五个数字< / b > :本地队列 256 格、每 61 次调度看一次全局队列、自旋 M 不超过忙碌 P 的一半、sysmon 至少 20 µs 醒一次、CPU 上连跑 10 ms 触发抢占。< / li >
< li > < b > 两条兜底< / b > : P 被系统调用借走 → < code > handoffp< / code > 转手(图 4) ; G 赖在 CPU 上不走 → < code > SIGURG< / code > 异步抢占(图 5) 。< / li >
< li > < b > 一条判据< / b > : < code > threads< / code > 涨而 < code > idlethreads< / code > 不涨 = 同步 I/O; < code > runqueue< / code > 涨而 CPU 不满 = 唤醒失衡或 G 太少; 两者都不是「goroutine 太多」。< / li >
< / ul >
2026-10-21 14:11:30 +08:00
< / div >
2026-10-25 11:57:02 +08:00
< p > 把这一章压成一句话:< strong > G 是任务与现场, M 是执行它的线程, P 是让它合法执行的许可与本地资源< / strong > 。调度循环永远是 < code > schedule< / code > → < code > findRunnable< / code > → < code > execute< / code > → < code > gogo< / code > ,让出时用 < code > mcall< / code > 回 g0; 本地队列挂在 P 上,全局队列兜底;系统调用卡住时 sysmon 下一个 tick 就会把 P 交出去,在 CPU 上跑太久才轮得到 < code > SIGURG< / code > 异步抢占。下一步进入内存分配:这些 G 在堆上申请对象时,< code > mcache< / code > 这个「挂在 P 上的本地资源」到底省掉了什么。< / p >
2026-10-21 14:11:30 +08:00
< / article >
< nav class = "pager" >
< a class = "prev" href = "01-goroutine.html" > < span class = "k" > ← 上一章< / span > < span class = "v" > 第 1 章 · 从进程到 goroutine: 并发模型的底层账本< / span > < / a >
< a class = "next" href = "03-memory.html" > < span class = "k" > 下一章 →< / span > < span class = "v" > 第 3 章 · 内存分配:从 mspan 到 mallocgc< / span > < / a >
< / nav >
< p class = "foot" >
Go 八股 · 第 2 章 GMP 调度器: Go 如何把十万个 goroutine 跑起来< br >
< a href = "index.html" > 总目录< / a > · < a href = "../../SRE工程师/sre-learning-path/index.html" > SRE 学习路径< / a >
< / p >
< / main >
< / div >
< button id = "toTop" title = "回到顶部" > ↑< / button >
< script src = "assets/doc.js" > < / script >
< script src = "../../assets/back.js" data-portal-back = "knowledge/go" data-portal-label = "知识库 › Go 八股知识库" > < / script >
< / body >
< / html >