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 > 第 1 章 从进程到 goroutine: 并发模型的底层账本 · Go 八股知识库< / title >
2026-10-25 11:57:02 +08:00
< meta name = "description" content = "按「现象 → 机制 → 代价」重讲 goroutine: 三种调度单位的差别、2KB 动态栈与复制扩容、newproc 与 gogo 的创建切换、GOMAXPROCS 的真实含义、阻塞时被卡住的是 G 还是 M, 并给出四张示意图与切换成本对比。" >
2026-10-21 14:11:30 +08:00
< 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 > 第 1 章< / 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" > < span class = "toc-a active" aria-current = "page" > < i class = "cn" > 1< / i > 从进程到 goroutine: 并发模型的底层账本< / span > < div class = "subnav current" > < a class = "toc-a lv3" href = "#sec-1-1" > 1.1 三种调度单位:进程、线程、协程< / a > < a class = "toc-a lv3" href = "#sec-1-2" > 1.2 goroutine 是什么: M:N 调度与 2KB 起步< / a > < a class = "toc-a lv3" href = "#sec-1-3" > 1.3 动态栈:不够就复制,闲着就收缩< / a > < a class = "toc-a lv3" href = "#sec-1-4" > 1.4 创建与切换: newproc、gogo 与 goexit< / a > < a class = "toc-a lv3" href = "#sec-1-5" > 1.5 GOMAXPROCS: 限制的不是 goroutine 数< / a > < a class = "toc-a lv3" href = "#sec-1-6" > 1.6 切换成本对比:为什么说 goroutine 便宜< / a > < a class = "toc-a lv3" href = "#sec-1-7" > 1.7 阻塞的代价:谁被卡住了< / a > < a class = "toc-a lv3" href = "#sec-1-8" > 1.8 工程用法:起 goroutine 之前先想好怎么退出< / a > < / div > < a class = "toc-a" href = "02-gmp.html" > < i class = "cn" > 2< / i > GMP 调度器: Go 如何把十万个 goroutine 跑起来< / a > < 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" > 1< / b > / 14 章< / span >
< / p >
< h2 id = "ch1" > < span class = "n" > 1< / span > 从进程到 goroutine: 并发模型的底层账本< / h2 >
2026-10-22 23:35:36 +08:00
< div class = "box ok" >
2026-10-25 11:57:02 +08:00
< span class = "bt" > 先给答案 · 30 秒版< / span >
< p > goroutine 是 Go 在用户态自己实现的协程,由 runtime 调度到少量内核线程上执行,属于 M:N 模型。它比线程轻,轻在三点:< strong > 初始栈只有 2 KB 而且能按需增长< / strong > ; < strong > 切换在用户态完成,不用陷进内核< / strong > ; < strong > 某个 goroutine 阻塞在系统调用时,它占的执行资源会被让出去< / strong > ,别的 goroutine 接着跑。所以单机开十万个 goroutine 是常态,换成线程早就 OOM 了。但 goroutine 不能被外部强行杀掉,也没有有意义的 ID——必须在代码里给它设计退出路径, 否则就是泄露。< / p >
2026-10-22 23:35:36 +08:00
< / div >
2026-10-21 14:11:30 +08:00
< div class = "lead" >
< b > 这一章解决什么:< / b > 面试里「goroutine 和线程有什么区别」几乎必问,但多数人只能答出「更轻」。
2026-10-25 11:57:02 +08:00
下面把「轻」拆成三笔账——< strong > 栈多大、切换保存什么、阻塞时谁买单< / strong > ——
每一笔都按同一个顺序讲:< strong > 先看现象,再拆机制,最后算代价< / strong > 。
读完你应该能解释:十万个 goroutine 为什么不会把内存吃穿、GOMAXPROCS 到底限制了谁、
2026-10-21 14:11:30 +08:00
以及一个没有退出路径的 goroutine 为什么会变成线上故障。
< / div >
2026-10-25 11:57:02 +08:00
< div class = "box note" >
< span class = "bt" > 怎么读这一章< / span >
< ul >
< li > < b > 每节结构一致< / b > : < span class = "tag" > 现象< / span > 你观察到的结果 → < span class = "tag" > 机制< / span > 运行时怎么做到的 → < span class = "tag" > 代价< / span > 什么时候会翻车 → 末尾一句小结。< / li >
< li > < b > 先看图中再看字< / b > :本章配了 4 张示意图,读懂图再读文字会快很多,因为这些东西本质上都是「谁移动到哪里」。< / li >
< li > < b > 标了 < span class = "tag s" > 可跳过< / span > 的段落< / b > 是面试加分细节(寄存器名、版本差异)。第一遍跳过不影响主线,第二遍再回来补。< / li >
< li > < b > 术语卡住就查下表< / b > ,不要硬扛着自己猜——本章的难读,八成是因为某个词还没落地就开始讲它了。< / li >
< / ul >
< / div >
< h4 > 术语速查(本章出现的核心词)< / h4 >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 术语< / th > < th > 一句话解释< / th > < th > 在哪节< / th > < / tr > < / thead >
< tbody >
< tr > < td > < code > G< / code > < / td > < td > goroutine 在运行时的数据结构。< b > 一个 G = 一套栈 + 一份寄存器现场< / b > ,就是一个待执行的函数调用< / td > < td > 1.2< / td > < / tr >
< tr > < td > < code > M< / code > < / td > < td > 操作系统线程,< b > 真正被内核调度< / b > 的单位。goroutine 最终必须跑在某个 M 上< / td > < td > 1.2< / td > < / tr >
< tr > < td > < code > P< / code > < / td > < td > 处理器(< b > 不是 CPU 核< / b > ),持有本地待运行队列。< b > G 必须先拿到 P 才能执行 Go 代码< / b > < / td > < td > 1.2 / 1.5< / td > < / tr >
< tr > < td > M:N 调度< / td > < td > 很多 G 复用到少量 M 上, P 是中间层。区别于 1:1( 线程模型) 和 N:1( 老式绿色线程) < / td > < td > 1.2< / td > < / tr >
< tr > < td > 用户态调度< / td > < td > 创建、切换、销毁全在进程内完成,不进内核、不产生系统调用< / td > < td > 1.1< / td > < / tr >
< tr > < td > 栈 stack< / td > < td > 每个 G 私有的连续内存,放局部变量和函数调用帧。可以搬家(复制)< / td > < td > 1.2 / 1.3< / td > < / tr >
< tr > < td > < code > sysmon< / code > < / td > < td > 运行时的后台监控线程,负责发现「跑了太久」和「卡在系统调用」的情况< / td > < td > 1.7< / td > < / tr >
< tr > < td > < code > netpoll< / code > < / td > < td > 网络轮询器(底层是 epoll/kqueue) , 让网络等待不占用线程< / td > < td > 1.7< / td > < / tr >
< tr > < td > handoff< / td > < td > 把 P 从卡住的 M 手里转交给别的 M, 好让队列里的 G 继续跑< / td > < td > 1.7< / td > < / tr >
< / tbody >
< / table >
< / div >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-1-1" > 1.1 三种调度单位:进程、线程、协程< / h3 >
2026-10-25 11:57:02 +08:00
< p > < span class = "tag" > 现象< / span > 同一台 8 核机器,开 10 万个 goroutine 稳稳当当;换成 10 万个线程,机器直接躺平。同样的「并发数量」,一个没事一个崩——差的是< b > 每个并发单位背后要花多少成本< / b > 。< / p >
< p > < span class = "tag" > 机制< / span > 先把三个词放回操作系统里。进程( process) 是< strong > 资源分配< / strong > 的基本单位: 独立的虚拟地址空间、文件描述符表、信号处理。线程( thread) 是 < strong > CPU 调度< / strong > 的基本单位: 同一进程内的线程共享地址空间, 但各自有一套寄存器和栈。协程( coroutine) 不是内核概念, 它是< strong > 用户态< / strong > 的任务单位——创建、切换、销毁都由程序自己的调度器决定,内核完全不知情。< / p >
< p > 「用户态调度」这四个字是全章所有结论的源头。内核调度线程要陷进内核态、保存完整上下文、可能切换页表;用户态调度只是在几个数据结构之间换指针,成本低一个数量级。差别就集中在下表的后三行。< / p >
2026-10-21 14:11:30 +08:00
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 维度< / th > < th > 进程< / th > < th > 线程< / th > < th > goroutine< / th > < / tr > < / thead >
< tbody >
< tr > < td > 调度者< / td > < td > 内核< / td > < td > 内核< / td > < td > Go runtime( 用户态) < / td > < / tr >
< tr > < td > 地址空间< / td > < td > 独立< / td > < td > 共享进程< / td > < td > 共享进程< / td > < / tr >
< tr > < td > 初始栈< / td > < td > 独立地址空间< / td > < td > 通常 1– 8 MB< / td > < td > < b > 2 KB< / b > ,可增长< / td > < / tr >
< tr > < td > 切换成本(量级)< / td > < td > 3– 10 µs< / td > < td > 1– 2 µs< / td > < td > 0.1– 0.3 µs< / td > < / tr >
< tr > < td > 单机数量级< / td > < td > 数十到数百< / td > < td > 数百到数千< / td > < td > 十万到百万< / td > < / tr >
< / tbody >
< / table >
< / div >
2026-10-25 11:57:02 +08:00
< p > 表里的数字会随机型变化, 但数量级关系稳定。面试时不要只背「goroutine 轻」,要能说出轻的三个来源:< strong > 栈小且按需增长< / strong > 、< strong > 切换不陷内核< / strong > 、< strong > 调度决策在用户态完成< / strong > 。后面三节就按这个顺序拆。< / p >
< p > < span class = "tag" > 代价< / span > 省下来的东西都要在别处还。内核替你干了两件事:保存上下文,以及< strong > 在阻塞时把 CPU 让出去< / strong > 。用户态调度器接了第一件,第二件必须自己想办法——某个协程一旦执行阻塞系统调用,背后的内核线程也会被卡住,调度器得把其他协程挪到别的线程上。这就是 1.7 节要还的那笔账,也是 Go 调度器复杂度的主要来源。< / p >
< p class = "take" > < b > 一句话:< / b > 线程的成本是「内核管着」, goroutine 的成本是「运行时自己管」——前者省心,后者省时间。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-1-2" > 1.2 goroutine 是什么: M:N 调度与 2KB 起步< / h3 >
2026-10-25 11:57:02 +08:00
< p > < span class = "tag" > 现象< / span > 「十万 goroutine 不会炸」到底是多大?不用猜,跑一段代码就能量出来:让十万个 goroutine 同时挂住,看栈内存涨了多少。< / p >
2026-10-21 14:11:30 +08:00
< pre data-lang = "go" data-name = "main.go: 十万个 goroutine 的栈占用" > package main
import (
"fmt"
"runtime"
"sync"
)
func main() {
var wg sync.WaitGroup
block := make(chan struct{})
var m1, m2 runtime.MemStats
runtime.GC()
runtime.ReadMemStats(& m1)
for i := 0; i < 100000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
< -block // 全部挂起,保证栈同时存在
}()
}
runtime.GC()
runtime.ReadMemStats(& m2)
fmt.Printf("goroutines=%d\n", runtime.NumGoroutine())
fmt.Printf("StackInuse: %.1f MB -> %.1f MB\n",
2026-10-21 15:21:43 +08:00
float64(m1.StackInuse)/(1< < 20), float64(m2.StackInuse)/(1< < 20))
2026-10-21 14:11:30 +08:00
close(block)
wg.Wait()
}< / pre >
2026-10-21 15:21:43 +08:00
< pre data-lang = "text" data-name = "本机输出( Go 1.25, Linux/amd64) " > goroutines=100001
2026-10-21 14:11:30 +08:00
StackInuse: 0.3 MB -> 204.9 MB< / pre >
2026-10-25 11:57:02 +08:00
< p > 约 205 MB, 正好是 10 万 × 2 KB 再加一点元数据。这个数字在 Windows 上会变成 780 MB 左右: Windows 的最小栈按分配粒度对齐到 8 KB, 同一份程序栈占用直接翻四倍。< mark > 量级不变, 但「2 KB」不是跨平台承诺< / mark > ——面试时能补这一句,说明你不是背的。< / p >
< p > < span class = "tag" > 机制< / span > 一个 G 在 < code > runtime/runtime2.go< / code > 里是个实打实的结构体,字段十来个;和这一节有关的只有三样:< b > 一段栈的区间< / b > 、< b > 一条栈水位线< / b > 、< b > 一份寄存器现场< / b > 。完整字段拆解放在 < a href = "02-gmp.html#sec-2-2" > 2.2 三个结构体< / a > , 这里只需记住一条: G 本身是个很小的对象,大头在它那 2 KB 的栈上。< / p >
< p > 为什么偏偏是 2 KB( < code > _StackMin = 2048< / code > )?因为要同时满足两件事:< b > 足够跑完一次普通函数调用链< / b > (不用立刻扩容),< b > 又足够小< / b > (这样十万个 G 的栈才只占 200 MB) 。线程栈默认 1– 8 MB, 是给「最坏情况的递归深度」留的余量, 代价就是每个线程都先付这笔钱。< / p >
< p > 还要注意:这 200 MB 不是「预留的虚拟地址」,是< b > 真分配出去的内存< / b > 。每个栈由 < code > stackalloc< / code > 从堆里取一块 span( 小栈来自 P 自带的 < code > stackcache< / code > ,大栈走 < code > mheap< / code > ),会计入 < code > StackInuse< / code > 。< / p >
< p > < span class = "tag" > 代价< / span > 「十万 goroutine 没炸」是真的, 「goroutine 不要钱」是假的。每个 G 至少 2 KB 栈加几百字节的 < code > g< / code > 结构,百万级就是 GB 级。< b > 能开十万,不等于该开十万。< / b > < / p >
< figure class = "figure" >
< svg viewBox = "0 0 900 350" role = "img" aria-label = "G、M、P 三层结构示意:大量 goroutine 经由少量处理器 P 复用到少量操作系统线程 M 上" >
< text x = "14" y = "46" font-size = "14.5" font-weight = "700" style = "fill:var(--ink)" > G · goroutine< / text >
< text x = "14" y = "68" font-size = "12.5" style = "fill:var(--muted)" > 十万量级< / text >
< text x = "14" y = "162" font-size = "14.5" font-weight = "700" style = "fill:var(--ink)" > P · 处理器< / text >
< text x = "14" y = "184" font-size = "12.5" style = "fill:var(--muted)" > 数量 = GOMAXPROCS< / text >
< text x = "14" y = "262" font-size = "14.5" font-weight = "700" style = "fill:var(--ink)" > M · 系统线程< / text >
< text x = "14" y = "284" font-size = "12.5" style = "fill:var(--muted)" > 真正被内核调度< / text >
< g style = "fill:var(--card);stroke:var(--brand)" >
< rect x = "168" y = "34" width = "64" height = "34" rx = "7" / >
< rect x = "246" y = "34" width = "64" height = "34" rx = "7" / >
< rect x = "324" y = "34" width = "64" height = "34" rx = "7" / >
< rect x = "402" y = "34" width = "64" height = "34" rx = "7" / >
< rect x = "480" y = "34" width = "64" height = "34" rx = "7" / >
< rect x = "558" y = "34" width = "64" height = "34" rx = "7" / >
< rect x = "636" y = "34" width = "64" height = "34" rx = "7" / >
< rect x = "714" y = "34" width = "64" height = "34" rx = "7" / >
< / g >
< g font-size = "13" style = "fill:var(--ink)" >
< text x = "200" y = "56" text-anchor = "middle" > G1< / text >
< text x = "278" y = "56" text-anchor = "middle" > G2< / text >
< text x = "356" y = "56" text-anchor = "middle" > G3< / text >
< text x = "434" y = "56" text-anchor = "middle" > G4< / text >
< text x = "512" y = "56" text-anchor = "middle" > G5< / text >
< text x = "590" y = "56" text-anchor = "middle" > G6< / text >
< text x = "668" y = "56" text-anchor = "middle" > G7< / text >
< text x = "746" y = "56" text-anchor = "middle" > G8< / text >
< text x = "800" y = "56" style = "fill:var(--muted)" > …< / text >
< / g >
< g style = "stroke:var(--brand)" stroke-width = "1.3" opacity = ".5" >
< line x1 = "200" y1 = "68" x2 = "283" y2 = "138" / >
< line x1 = "278" y1 = "68" x2 = "305" y2 = "138" / >
< line x1 = "356" y1 = "68" x2 = "327" y2 = "138" / >
< line x1 = "434" y1 = "68" x2 = "463" y2 = "138" / >
< line x1 = "512" y1 = "68" x2 = "485" y2 = "138" / >
< line x1 = "590" y1 = "68" x2 = "643" y2 = "138" / >
< line x1 = "668" y1 = "68" x2 = "665" y2 = "138" / >
< line x1 = "746" y1 = "68" x2 = "687" y2 = "138" / >
< / g >
< g style = "fill:var(--brand-soft);stroke:var(--brand)" >
< rect x = "250" y = "138" width = "110" height = "46" rx = "8" / >
< rect x = "430" y = "138" width = "110" height = "46" rx = "8" / >
< rect x = "610" y = "138" width = "110" height = "46" rx = "8" / >
< / g >
< g font-size = "13.5" font-weight = "700" style = "fill:var(--brand-ink)" >
< text x = "305" y = "167" text-anchor = "middle" > P0< / text >
< text x = "485" y = "167" text-anchor = "middle" > P1< / text >
< text x = "665" y = "167" text-anchor = "middle" > P2< / text >
< / g >
< g style = "stroke:var(--muted)" stroke-width = "1.6" >
< line x1 = "305" y1 = "184" x2 = "305" y2 = "238" / >
< line x1 = "485" y1 = "184" x2 = "485" y2 = "238" / >
< line x1 = "665" y1 = "184" x2 = "665" y2 = "238" / >
< / g >
< g style = "fill:var(--card);stroke:var(--line)" >
< rect x = "250" y = "238" width = "110" height = "46" rx = "8" / >
< rect x = "430" y = "238" width = "110" height = "46" rx = "8" / >
< rect x = "610" y = "238" width = "110" height = "46" rx = "8" / >
< / g >
< g font-size = "13.5" style = "fill:var(--muted)" >
< text x = "305" y = "267" text-anchor = "middle" > M0< / text >
< text x = "485" y = "267" text-anchor = "middle" > M1< / text >
< text x = "665" y = "267" text-anchor = "middle" > M2< / text >
< / g >
< rect x = "150" y = "304" width = "740" height = "34" rx = "8" style = "fill:var(--soft);stroke:var(--line)" / >
< text x = "520" y = "326" font-size = "12.5" text-anchor = "middle" style = "fill:var(--muted)" > 内核: M 被调度到 CPU 核上, G 只在 M 上短暂运行< / text >
< / svg >
< p class = "figcap" > < b > 图 1 · G 在 P 上排队, P 被 M 持有。< / b > 箭头是「谁排在谁那儿」, 不是「谁属于谁」——G 可以在任意 P 之间流动, P 也可以被换到别的 M 上。< / p >
< / figure >
< p > 图中这层 < b > P 常常被忽略,但它才是后面所有性能讨论的主角< / b > : G 必须先拿到一个 P, 才能执行 Go 代码。所以「同时有几个 goroutine 在跑」由 P 的数量决定,而 P 的数量就等于 GOMAXPROCS( 见 1.5)。< / p >
< div class = "box note" >
2026-10-21 14:11:30 +08:00
< span class = "bt" > goroutine 没有对外 ID, 是设计选择不是缺失< / span >
2026-10-25 11:57:02 +08:00
< p > 运行时内部有 < code > goid< / code > ,供 trace、pprof 和调试使用,但没有公开 API 能拿到它。官方明确反对「goroutine-local storage」: 一旦代码依赖「当前是哪个 goroutine」, 就无法安全地跨 goroutine 复用、也无法在调度器迁移 G 时保持语义。需要请求级数据时用 < code > context.Context< / code > 显式传递,见 < a href = "11-context.html#sec-11-5" > 11.5< / a > 。< / p >
2026-10-21 14:11:30 +08:00
< / div >
2026-10-25 11:57:02 +08:00
< p class = "take" > < b > 一句话:< / b > goroutine 便宜是因为「起步只要 2 KB」而不是「不要内存」; P 的数量决定同一时刻能跑几个。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-1-3" > 1.3 动态栈:不够就复制,闲着就收缩< / h3 >
2026-10-25 11:57:02 +08:00
< p > < span class = "tag" > 现象< / span > 一个函数第一版只用几十字节栈空间,第二版在里面加了个 8 KB 的大数组,程序行为完全不变,也没报错——< b > 栈自己长大了< / b > ,而且是运行期长,不是编译期定好的。< / p >
< p > < span class = "tag" > 机制< / span > 编译器在每个函数的入口(序言 prologue) 插一小段检查: 把当前栈指针和 < code > stackguard0< / code > 比一比,剩余空间不够就调用 < code > runtime.morestack< / code > 。< code > morestack< / code > 跑在 < code > g0< / code > (每个 M 自带的调度栈,不占用用户代码的栈)上,由它调用 < code > newstack< / code > 完成搬家:< / p >
2026-10-21 14:11:30 +08:00
< ol class = "steps" >
< li > 分配一块新栈,大小是旧栈的两倍(有上限);< / li >
< li > 把旧栈上的内容整块复制过去;< / li >
2026-10-25 11:57:02 +08:00
< li > 遍历旧栈, 按栈映射( stack map) 把每个指向旧栈的指针改到新栈; < / li >
< li > 回到新栈,接着执行刚才那个函数。< / li >
2026-10-21 14:11:30 +08:00
< / ol >
2026-10-25 11:57:02 +08:00
< figure class = "figure" >
< svg viewBox = "0 0 900 350" role = "img" aria-label = "栈扩容复制示意:旧栈 2KB 用满后分配 4KB 新栈,复制内容并按栈映射改写指针,旧地址全部失效" >
< text x = "40" y = "34" font-size = "14" font-weight = "700" style = "fill:var(--ink)" > ① 旧栈: 2 KB, 快用满< / text >
< rect x = "120" y = "56" width = "150" height = "210" rx = "8" style = "fill:var(--card);stroke:var(--line)" / >
< rect x = "120" y = "166" width = "150" height = "100" style = "fill:var(--brand-soft);stroke:var(--brand)" / >
< line x1 = "100" y1 = "166" x2 = "286" y2 = "166" stroke-dasharray = "5 4" style = "stroke:var(--warn)" stroke-width = "1.5" / >
< text x = "28" y = "160" font-size = "11.5" style = "fill:var(--warn)" > stackguard0< / text >
< text x = "195" y = "222" font-size = "12" text-anchor = "middle" style = "fill:var(--brand-ink)" > 已用 1.9 KB< / text >
< g style = "fill:var(--accent)" >
< circle cx = "155" cy = "188" r = "5" / >
< circle cx = "195" cy = "212" r = "5" / >
< circle cx = "235" cy = "236" r = "5" / >
< / g >
< text x = "195" y = "292" font-size = "12" text-anchor = "middle" style = "fill:var(--muted)" > 三个变量的地址: 0xc0001a00 …< / text >
< line x1 = "300" y1 = "160" x2 = "530" y2 = "160" style = "stroke:var(--brand)" stroke-width = "2.2" / >
< polygon points = "530,160 518,154 518,166" style = "fill:var(--brand)" / >
< text x = "415" y = "142" font-size = "12.5" text-anchor = "middle" style = "fill:var(--brand-ink)" > morestack → newstack< / text >
< text x = "415" y = "184" font-size = "12" text-anchor = "middle" style = "fill:var(--muted)" > 复制内容 + 按栈映射改指针< / text >
< text x = "560" y = "34" font-size = "14" font-weight = "700" style = "fill:var(--ink)" > ② 新栈: 4 KB, 地址全变了< / text >
< rect x = "560" y = "40" width = "200" height = "226" rx = "8" style = "fill:var(--card);stroke:var(--brand)" / >
< rect x = "560" y = "166" width = "200" height = "100" style = "fill:var(--brand-soft);stroke:var(--brand)" / >
< text x = "660" y = "222" font-size = "12" text-anchor = "middle" style = "fill:var(--brand-ink)" > 内容一样,位置不同< / text >
< g style = "fill:var(--accent)" >
< circle cx = "610" cy = "188" r = "5" / >
< circle cx = "660" cy = "212" r = "5" / >
< circle cx = "710" cy = "236" r = "5" / >
< / g >
< text x = "660" y = "292" font-size = "12" text-anchor = "middle" style = "fill:var(--muted)" > 同样的变量,现在是 0xc0004e00 …< / text >
< path d = "M640 300 L640 314 L235 314 L235 302" fill = "none" stroke-dasharray = "5 4" style = "stroke:var(--danger)" stroke-width = "1.5" / >
< polygon points = "235,302 229,312 241,312" style = "fill:var(--danger)" / >
< text x = "437" y = "334" font-size = "12" text-anchor = "middle" style = "fill:var(--danger)" > 旧地址失效:没被改写的指针(存在堆上、或塞进 uintptr) 就成了野指针< / text >
< / svg >
< p class = "figcap" > < b > 图 2 · 扩容的本质是搬家。< / b > runtime 会把旧栈上所有指针改到新地址,但只改它< b > 看得见< / b > 的那些——堆上抄走的地址、< code > uintptr< / code > 里存的整数,它都无从得知。< / p >
< / figure >
< p > 「搬家」这个比喻要抓住一点:< strong > 旧地址全部失效< / strong > 。这也是 Go 要求栈上指针必须能被运行时精确识别的原因——不精确,就改不干净。< / p >
< p > < span class = "tag" > 代价< / span > 三条边界,一条比一条容易踩。< / p >
< ul >
< li > < b > 栈地址会变< / b > :用 < code > unsafe.Pointer< / code > 把栈地址存到堆上、或用 < code > uintptr< / code > 长期保存地址,复制之后就变成野指针。这类 bug 只在栈恰好扩容时出现,极难复现。< / li >
< li > < b > 栈有上限< / b > : 64 位平台 1 GB, 超过直接 < code > fatal error: stack overflow< / code > ,这个错误< strong > 不能被 recover< / strong > 。< / li >
< li > < b > 收缩只在 GC 时< / b > :运行时扫描每个 G 的栈,发现只用了不到 1/4 就缩小一半(不低于 2 KB) 。所以「处理过大对象之后一直空闲」不会永久占着大栈, 但代价是要再复制一次——用「偶发的复制成本」换「长期的内存占用」。< / li >
< / ul >
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 > 一句话: Go 的栈是可移动的,运行时在复制栈时按栈映射重写所有指向旧栈的指针;因此栈地址不能长期保存在堆上或 < code > uintptr< / code > 里。再补一句「栈上限 1 GB, 溢出是 fatal, recover 不了」,基本就答满了。< / p >
2026-10-21 14:11:30 +08:00
< / div >
2026-10-25 11:57:02 +08:00
< p class = "take" > < b > 一句话:< / b > 栈便宜是因为「按需增长」,代价是「地址会变」——所以 Go 对指针格外敏感。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-1-4" > 1.4 创建与切换: newproc、gogo 与 goexit< / h3 >
2026-10-25 11:57:02 +08:00
< p > < span class = "tag" > 现象< / span > < code > go f(x)< / code > 只是一条普通语句:执行它不产生任何系统调用,也不创建内核对象。所以在循环里连起十万个 goroutine, 你感觉不到「创建」的开销——< b > 真正的工作被推迟到了调度器手上< / b > 。< / p >
< p > < span class = "tag" > 机制< / span > 编译器把 < code > go f(x)< / code > 翻译成一次 < code > runtime.newproc< / code > 调用,它只做四件事:< / p >
2026-10-21 14:11:30 +08:00
< ul >
2026-10-25 11:57:02 +08:00
< li > 从当前 P 的空闲列表 < code > gfree< / code > 里取一个闲置的 < code > g< / code > ,没有就新建(< code > malg< / code > ) ; < / li >
< li > 给它分配 2 KB 栈,把入口函数和参数压进去,把 < code > g.sched.pc< / code > 设成 < code > goexit< / code > ——< b > 这样函数返回时会自动回到 goexit, 而不是返回到一个不存在的调用者< / b > ; < / li >
< li > 状态设为 < code > _Grunnable< / code > ,塞进 < code > runnext< / code > 槽位(下一个就轮到它跑),原来占着 < code > runnext< / code > 的 G 被挤回本地队列尾部;< / li >
< li > 本地队列满了就转移一半到全局队列;必要时唤醒或创建新的 M。< / li >
2026-10-21 14:11:30 +08:00
< / ul >
2026-10-25 11:57:02 +08:00
< p > < code > runnext< / code > 这个细节值得记:它让「< code > go< / code > 之后立刻阻塞等待」的常见写法(比如 < code > go func(){...}(); ch < - x< / code > )能马上跑起新 G, 省掉一次排队。它的完整语义( 什么时候插、被挤下去的 G 去哪)见 < a href = "02-gmp.html#sec-2-4" > 2.4 本地队列< / a > 。< / p >
< p > 真正的「切换」发生在调度点。运行时用 < code > gogo< / code > 从 < code > g.sched< / code > 里恢复现场,然后< b > 直接跳转< / b > 到上次停下的位置继续执行;反过来,当前 G 要主动让出 CPU 时走 < code > mcall< / code > :把现场存进 < code > g.sched< / code > ,切到 < code > g0< / code > 栈上执行调度逻辑,再从队列里挑下一个 G。< / p >
< div class = "box warn" >
< span class = "bt" > 可跳过 · 寄存器级细节< / span >
< p > 准确的说法是:< code > gogo< / code > 恢复 < code > sp< / code > 、< code > bp< / code > ,把 g 自身装回 < code > R14< / code > ( Go 专门留的 g 寄存器)、把 < code > gobuf.ctxt< / code > 装进 < code > DX< / code > ,最后 < code > JMP< / code > 到 < code > gobuf.pc< / code > ——是跳转,不是 < code > RET< / code > 。这些名字对面试几乎无用,< b > 记住结论就够了< / b > :切换时只保存 < b > SP、PC、BP< / b > 这几个指针(外加 g 与 ctxt) , 不是保存全部通用寄存器。原因是 goroutine 只在< b > 安全点< / b > 切换,编译器在这些点上已经把活跃寄存器写回了栈,所以恢复栈指针和返回地址就够。线程切换要由内核保存完整上下文(含浮点/SIMD 状态和内核栈),差别就在这儿。< / p >
< / div >
< p > G 的终点是 < code > goexit< / code > :函数体跑完后进入 < code > goexit1< / code > ,把状态改成 < code > _Gdead< / code > 、清空字段、放回 < code > gfree< / code > 复用。所以< b > 创建和销毁基本都不经过内核< / b > ,只有栈内存的分配会走 < code > stackalloc< / code > 。< / p >
< figure class = "figure" >
< svg viewBox = "0 0 900 300" role = "img" aria-label = "一个 goroutine 的生命周期:创建、被调度执行、让出、结束回收" >
< g style = "fill:var(--card);stroke:var(--brand)" >
< rect x = "20" y = "48" width = "190" height = "96" rx = "10" / >
< rect x = "240" y = "48" width = "190" height = "96" rx = "10" / >
< rect x = "460" y = "48" width = "190" height = "96" rx = "10" / >
< rect x = "680" y = "48" width = "190" height = "96" rx = "10" / >
< / g >
< g font-size = "13" font-weight = "700" style = "fill:var(--brand)" >
< text x = "36" y = "72" > ① _Grunnable< / text >
< text x = "256" y = "72" > ② _Grunning< / text >
< text x = "476" y = "72" > ③ 让出< / text >
< text x = "696" y = "72" > ④ _Gdead< / text >
< / g >
< g font-size = "12.5" style = "fill:var(--muted)" >
< text x = "36" y = "98" > go f() → newproc< / text >
< text x = "36" y = "118" > 取/建 g、分配 2 KB 栈< / text >
< text x = "36" y = "136" > 塞进 runnext 排队< / text >
< text x = "256" y = "98" > gogo 恢复 SP/PC/BP< / text >
< text x = "256" y = "118" > 开始执行你的函数< / text >
< text x = "256" y = "136" > 全程不陷内核< / text >
< text x = "476" y = "98" > gopark( 等 chan 或锁)< / text >
< text x = "476" y = "118" > entersyscall( 系统调用) < / text >
< text x = "476" y = "136" > 或 被抢占< / text >
< text x = "696" y = "98" > 函数返回 → goexit< / text >
< text x = "696" y = "118" > 清空现场、放回 gfree< / text >
< text x = "696" y = "136" > 下次 go 时复用< / text >
< / g >
< g style = "stroke:var(--brand)" stroke-width = "2" >
< line x1 = "210" y1 = "96" x2 = "234" y2 = "96" / >
< line x1 = "430" y1 = "96" x2 = "454" y2 = "96" / >
< line x1 = "650" y1 = "96" x2 = "674" y2 = "96" / >
< / g >
< g style = "fill:var(--brand)" >
< polygon points = "240,96 228,90 228,102" / >
< polygon points = "460,96 448,90 448,102" / >
< polygon points = "680,96 668,90 668,102" / >
< / g >
< path d = "M555 144 L555 214 L335 214 L335 150" fill = "none" style = "stroke:var(--ok)" stroke-width = "2" / >
< polygon points = "335,150 329,162 341,162" style = "fill:var(--ok)" / >
< text x = "445" y = "236" font-size = "12.5" text-anchor = "middle" style = "fill:var(--ok)" > 被唤醒 / 系统调用返回 → 重新排队,等待再次被选中< / text >
< text x = "445" y = "272" font-size = "12" text-anchor = "middle" style = "fill:var(--muted)" > 一个 G 一生可以被调度成千上万次,状态就在 ①②③ 之间来回< / text >
< / svg >
< p class = "figcap" > < b > 图 3 · 一个 G 的一生。< / b > 只有 ④ 是终点;①②③ 之间的往返不涉及内核,也不涉及内存分配。< / p >
< / figure >
< p > < span class = "tag" > 代价< / span > 因为只在安全点切换, goroutine 的切换才那么便宜;< b > 但也正因为只在安全点切换< / b > ,一段纯计算、不带任何函数调用的死循环本来永远轮不到别人——需要异步抢占来兜底(见 1.7)。这是「协作式」与「抢占式」的分界线,面试经常在这里设坑。< / p >
< p class = "take" > < b > 一句话:< / b > 创建是把 g 塞进队列,切换是换个栈指针继续跳,销毁是放回池子——三步都在用户态。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-1-5" > 1.5 GOMAXPROCS: 限制的不是 goroutine 数< / h3 >
2026-10-25 11:57:02 +08:00
< p > < span class = "tag" > 现象< / span > 8 核机器上 < code > runtime.GOMAXPROCS(0)< / code > 返回 8, 符合直觉。但把它跑在限制 2 核的 Pod 里, Go 1.24 及以前返回的却是< b > 宿主机核数< / b > ,比如 64——程序以为自己有 64 个核可以用。< / p >
< p > < span class = "tag" > 机制< / span > < code > GOMAXPROCS< / code > 限制的是< strong > 同时执行 Go 代码的 M 的数量< / strong > ,等价于「活跃 P 的数量」。goroutine 可以有几十万个,但同一时刻最多只有 GOMAXPROCS 个真的在 CPU 上跑,其余在队列里等。< / p >
2026-10-21 14:11:30 +08:00
< pre data-lang = "go" data-name = "main.go: 读取与设置 GOMAXPROCS" > package main
import (
"fmt"
"runtime"
)
func main() {
fmt.Println("NumCPU =", runtime.NumCPU())
fmt.Println("GOMAXPROCS =", runtime.GOMAXPROCS(0)) // 传 0 表示只读
runtime.GOMAXPROCS(4) // 例如在 8 核机器上限制为 4
fmt.Println("after set =", runtime.GOMAXPROCS(0))
}< / pre >
< pre data-lang = "text" data-name = "8 核机器输出" > NumCPU = 8
GOMAXPROCS = 8
after set = 4< / pre >
2026-10-25 11:57:02 +08:00
< p > 默认值在 < b > 1.25 起< / b > 不再直接等于 < code > runtime.NumCPU()< / code > :取「逻辑 CPU 数」与「cgroup CPU 带宽配额( quota / period, 小数向上取整、结果小于 2 时按 2 算)」中的较小值,运行期还会周期性复核。用环境变量或 API 手工设过之后,这两项自动行为都会关闭。< / p >
< p > < span class = "tag" > 代价< / span > 容器里那个经典坑:< b > Go 1.24 及以前只看宿主机逻辑 CPU 数< / b > 。一个限制 2 核的 Pod 跑在 64 核宿主机上,< code > GOMAXPROCS< / code > 会是 64, 于是 GC 后台标记、调度队列都按 64 核铺开, CPU 被限流后延迟反而变差。< b > 1.25 起< / b > 默认值改成按 cgroup 配额取较小值,还能周期跟着配额调整;不想要这两项行为可以分别关掉:< code > GODEBUG=containermaxprocs=0< / code > (不读配额)、< code > updatemaxprocs=0< / code > (不周期更新)。在 1.24 及以前,这类部署普遍靠 < code > go.uber.org/automaxprocs< / code > 在启动时读配额,< strong > 那部分老项目仍然需要它< / strong > 。< / p >
2026-10-21 14:11:30 +08:00
< div class = "box danger" >
< span class = "bt" > GOMAXPROCS=1 不等于「单线程」< / span >
2026-10-25 11:57:02 +08:00
< p > 它只限制执行用户 Go 代码的 P 数。sysmon 监控线程、网络轮询( netpoll) 、cgo 调用都跑在别的线程上,阻塞系统调用也会让 M 带着 G 脱离 P。但 GC 的 mark worker 不算:它必须先拿到一个 P 才能开始 drain( < code > gcDrain< / code > 的前提就是持有 P) , GOMAXPROCS=1 时不会多出一个线程并行标记,只会把标记时间摊进那唯一的 P 里——内存只有几 MB、又限成 1 个 P 的容器, GC 反而更慢。面试里把「GOMAXPROCS 是 P 的数量」说清楚,比背默认值更加分。< / p >
2026-10-21 14:11:30 +08:00
< / div >
2026-10-25 11:57:02 +08:00
< p class = "take" > < b > 一句话:< / b > 它管的是「几个 P 在跑 Go 代码」,不是「能开几个 goroutine」。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-1-6" > 1.6 切换成本对比:为什么说 goroutine 便宜< / h3 >
2026-10-25 11:57:02 +08:00
< p > < span class = "tag" > 现象< / span > 同样一次「让出 CPU 再回来」,线程要 1– 2 µs, goroutine 只要 0.1– 0.3 µs, 差一个数量级。差在哪? < / p >
< p > < span class = "tag" > 机制< / span > 把「切换」拆成三笔开销:< strong > 陷入内核< / strong > 、< strong > 保存/恢复上下文< / strong > 、< strong > 污染缓存< / strong > 。线程切换三样全占; goroutine 切换把前两样基本省掉,第三样只是「轻一些」而不是「没有」。< / p >
2026-10-21 14:11:30 +08:00
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 对比项< / th > < th > 线程切换< / th > < th > goroutine 切换< / th > < / tr > < / thead >
< tbody >
< tr > < td > 触发方式< / td > < td > 内核抢占/阻塞< / td > < td > 函数调用、channel、GC、抢占信号< / td > < / tr >
< tr > < td > 特权级< / td > < td > 用户态 → 内核态 → 用户态< / td > < td > 始终用户态< / td > < / tr >
< tr > < td > 保存内容< / td > < td > 全部寄存器 + 内核栈 + FPU/SIMD< / td > < td > SP/PC/BP 等少量现场< / td > < / tr >
< tr > < td > 栈< / td > < td > 固定 1– 8 MB< / td > < td > 2 KB 起,按需复制增长< / td > < / tr >
< tr > < td > 典型耗时< / td > < td > 1– 2 µs< / td > < td > 0.1– 0.3 µs< / td > < / tr >
< / tbody >
< / table >
< / div >
2026-10-25 11:57:02 +08:00
< p > < span class = "tag" > 代价< / span > 别把这 0.1 µs 当成万能理由:< b > 便宜的是「切换」,不是「阻塞」< / b > 。切换快只能说明「让出去再接回来」很便宜,省不掉你等待本身的时间。一次 10 ms 的等待,换一万次也没救。真正决定并发能力的是「等待期间别人能不能继续干活」——这正是 1.7 的主题。< / p >
< div class = "box note" >
< span class = "bt" > 可跳过 · 和 Java 虚拟线程的区别< / span >
< p > Java 21 的虚拟线程( virtual thread) 走的是同一条路: JDK 把虚拟线程挂在载体线程( carrier thread) 上, 阻塞时卸载( unmount) , 栈以 chunk 形式放在堆里。区别在于 Go 的调度器是语言运行时内置的,虚拟线程则由 < code > ForkJoinPool< / code > 承载,而且遇到 < code > synchronized< / code > 或 native 调用会「钉住」( pinning) 。被问到时答一句就够: 「都是 M:N + 用户态栈, Go 的栈可复制增长、虚拟线程栈是堆上的 chunk; Go 没有 pinning 概念,但 cgo 会占住 M」。< / p >
< / div >
< p class = "take" > < b > 一句话:< / b > 省掉的是「进内核 + 存全部现场」,省不掉的是「你等的时间」。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-1-7" > 1.7 阻塞的代价:谁被卡住了< / h3 >
2026-10-25 11:57:02 +08:00
< p > < span class = "tag" > 现象< / span > 同样叫「阻塞」,代价能差三个数量级:从 channel 里读一个值,只是当前 G 挂起;而读一个普通文件,可能把整个 P 拖下水。< b > 判断代价的唯一方法,是问「被卡住的是 G、M, 还是 P」。< / b > < / p >
< p > < span class = "tag" > 机制< / span > 三种阻塞,运行时的应对完全不同:< / p >
2026-10-21 14:11:30 +08:00
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 阻塞类型< / th > < th > 被卡住的对象< / th > < th > 运行时怎么补救< / th > < / tr > < / thead >
< tbody >
< tr > < td > channel / mutex / < code > time.Sleep< / code > < / td > < td > G< / td > < td > < code > gopark< / code > 把 G 挂起, M 继续跑别的 G< / td > < / tr >
< tr > < td > 网络 I/O< / td > < td > G< / td > < td > 交给 netpoll( epoll/kqueue) , G 挂起, M 不阻塞< / td > < / tr >
2026-10-25 11:57:02 +08:00
< tr > < td > 文件 / 阻塞系统调用< / td > < td > M< / td > < td > P 被 < code > handoff< / code > 给其他 M, 返回时再抢 P< / td > < / tr >
2026-10-21 14:11:30 +08:00
< tr > < td > cgo 调用< / td > < td > M< / td > < td > 同上,且 cgo 期间不参与 GC 栈扫描< / td > < / tr >
< / tbody >
< / table >
< / div >
2026-10-25 11:57:02 +08:00
< figure class = "figure" >
< svg viewBox = "0 0 900 300" role = "img" aria-label = "三种阻塞情形下 G、M、P 各自的状态" >
< text x = "150" y = "26" font-size = "13.5" font-weight = "700" text-anchor = "middle" style = "fill:var(--ink)" > channel / mutex / sleep< / text >
< text x = "450" y = "26" font-size = "13.5" font-weight = "700" text-anchor = "middle" style = "fill:var(--ink)" > 网络 I/O< / text >
< text x = "750" y = "26" font-size = "13.5" font-weight = "700" text-anchor = "middle" style = "fill:var(--ink)" > 文件 / 阻塞系统调用< / text >
< g font-size = "12.5" font-weight = "700" style = "fill:var(--muted)" >
< text x = "44" y = "76" > G< / text > < text x = "44" y = "136" > M< / text > < text x = "44" y = "196" > P< / text >
< / g >
< g style = "stroke:var(--line)" >
< line x1 = "16" y1 = "102" x2 = "884" y2 = "102" stroke-dasharray = "4 6" / >
< line x1 = "16" y1 = "162" x2 = "884" y2 = "162" stroke-dasharray = "4 6" / >
< / g >
< g font-size = "12.5" >
< rect x = "64" y = "48" width = "172" height = "34" rx = "7" style = "fill:var(--warn-bg);stroke:var(--warn-line)" / >
< text x = "150" y = "70" text-anchor = "middle" style = "fill:var(--warn)" > 挂起( gopark) < / text >
< rect x = "64" y = "108" width = "172" height = "34" rx = "7" style = "fill:var(--ok-bg);stroke:var(--ok-line)" / >
< text x = "150" y = "130" text-anchor = "middle" style = "fill:var(--ok)" > 继续跑别的 G< / text >
< rect x = "64" y = "168" width = "172" height = "34" rx = "7" style = "fill:var(--ok-bg);stroke:var(--ok-line)" / >
< text x = "150" y = "190" text-anchor = "middle" style = "fill:var(--ok)" > 还在 M 手上< / text >
< rect x = "364" y = "48" width = "172" height = "34" rx = "7" style = "fill:var(--warn-bg);stroke:var(--warn-line)" / >
< text x = "450" y = "70" text-anchor = "middle" style = "fill:var(--warn)" > 挂起,交给 netpoll< / text >
< rect x = "364" y = "108" width = "172" height = "34" rx = "7" style = "fill:var(--ok-bg);stroke:var(--ok-line)" / >
< text x = "450" y = "130" text-anchor = "middle" style = "fill:var(--ok)" > 继续跑别的 G< / text >
< rect x = "364" y = "168" width = "172" height = "34" rx = "7" style = "fill:var(--ok-bg);stroke:var(--ok-line)" / >
< text x = "450" y = "190" text-anchor = "middle" style = "fill:var(--ok)" > 还在 M 手上< / text >
< rect x = "664" y = "48" width = "172" height = "34" rx = "7" style = "fill:var(--danger-bg);stroke:var(--danger-line)" / >
< text x = "750" y = "70" text-anchor = "middle" style = "fill:var(--danger)" > 跟着 M 一起卡住< / text >
< rect x = "664" y = "108" width = "172" height = "34" rx = "7" style = "fill:var(--danger-bg);stroke:var(--danger-line)" / >
< text x = "750" y = "130" text-anchor = "middle" style = "fill:var(--danger)" > 卡在系统调用里< / text >
< rect x = "664" y = "168" width = "172" height = "34" rx = "7" style = "fill:var(--brand-soft);stroke:var(--brand)" / >
< text x = "750" y = "190" text-anchor = "middle" style = "fill:var(--brand-ink)" > 被 handoff 转走< / text >
< / g >
< text x = "450" y = "240" font-size = "12.5" text-anchor = "middle" style = "fill:var(--muted)" > 前两种: G 挂起,线程资源没被白白占住。第三种:线程真的卡住了,只能靠「把 P 转手」来止损。< / text >
< text x = "450" y = "268" font-size = "12.5" text-anchor = "middle" style = "fill:var(--danger)" > 如果所有 M 都被系统调用卡住,队列里的 G 就没人跑了——这才是并发掉底的原因。< / text >
< / svg >
< p class = "figcap" > < b > 图 4 · 同样叫阻塞,被卡住的东西不同。< / b > 排查线上「CPU 没满但吞吐上不去」时,先看 pprof 里 Goroutine 视图卡在哪一类。< / p >
< / figure >
< p > 最危险的是「M 被卡住但 P 没交出去」。运行时为此专门养了一个后台线程 < code > sysmon< / code > :它不绑 P, 隔一小段时间醒一次( 空闲时 20 µs, 越闲间隔越长) , 专门检查有没有 M 抱着 P 进了内核,发现了就把这个 P 转手给别人。所以判断系统调用的代价, 问题从来不是「M 会不会被卡住」——它一定会——而是< b > 「P 有没有及时转手」< / b > :转得及时,代价只是浪费一个线程;转不及时,队列里的 G 就跟着一起停摆。排查入口是 < code > GODEBUG=schedtrace< / code > ,看 < code > threads< / code > 涨而 < code > idlethreads< / code > 不涨,就是这类负载的指纹。< code > reentersyscall< / code > → < code > retake< / code > → < code > handoffp< / code > → < code > exitsyscall< / code > 的完整流程,以及 1.25 与 1.26 在解绑方式上的差异,见 < a href = "02-gmp.html#sec-2-5" > 2.5 系统调用< / a > 。< / p >
< p > < span class = "tag" > 代价< / span > 「goroutine 阻塞不影响别人」是有条件的,条件是这个阻塞< b > 能被运行时识别并挂起< / b > 。CPU 密集的忙等、死循环、< code > unsafe< / code > 操作里的长临界区都不会主动让出,只能等< b > 异步抢占< / b > ( Go 1.14+):运行时给 M 发 < code > SIGURG< / code > ,信号处理把线程上下文改写成「刚调用过 < code > asyncPreempt< / code > 」的样子,于是一条纯计算、不带任何函数调用的循环也能在异步安全点被停下。函数入口检查 < code > stackguard0< / code > 是< b > 协作式< / b > 抢占的入口( G 自己走到下一个函数入口才让出),两者不要混为一谈。< / 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 > < b > 协作式< / b > : G 走到函数入口,自己发现该让了 → 靠 < code > stackguard0< / code > 检查。< b > 异步式< / b > : G 一直在循环里不回来 → 靠 < code > SIGURG< / code > 从外部打断。前者需要代码配合(有函数调用),后者不需要。< b > 说清这个区别< / b > , 就比「Go 支持抢占」四个字具体得多。详见 < a href = "02-gmp.html#sec-2-7" > 2.7< / a > 。< / p >
2026-10-21 14:11:30 +08:00
< / div >
2026-10-25 11:57:02 +08:00
< p class = "take" > < b > 一句话:< / b > 阻塞不可怕,可怕的是「卡住的东西没人接手」——所以先分清被卡住的是 G、M 还是 P。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-1-8" > 1.8 工程用法:起 goroutine 之前先想好怎么退出< / h3 >
2026-10-25 11:57:02 +08:00
< p > < span class = "tag" > 现象< / span > 线上最常见的 Go 故障不是死锁,而是< b > goroutine 泄露< / b > :请求结束了,后台 goroutine 还挂在 channel 发送、< code > time.Sleep< / code > 或阻塞 I/O 上,数量随 QPS 线性增长,最后 OOM。< / p >
< div class = "box case" >
< span class = "bt" > 真实案例: goroutine 从 2k 涨到 200k< / span >
< p > 某服务每次请求起一个后台 goroutine 写审计日志,日志队列满了就阻塞在 < code > ch < - entry< / code > 。下游 Kafka 抖动后队列不再消费, goroutine 全部堆在发送处;由于没有 < code > ctx< / code > 也没有超时, 它们永远不会退出。pprof 的 goroutine 视图显示 98% 的 G 停在 < code > chan send< / code > ,内存随请求量线性上涨。修复方式不是「加大队列」,而是给发送加 < code > select + ctx.Done()< / code > 、队列满时降级丢弃并打点。< b > 教训:有缓冲 channel 不是无限缓冲,阻塞发送必须有退出路径。< / b > < / p >
< / div >
< p > < span class = "tag" > 机制< / span > 写并发代码前先回答四个问题,答不上来就别写 < code > go< / code > : < / p >
2026-10-21 14:11:30 +08:00
< div class = "cards" >
< div class = "card" >
< h4 > 谁负责让它退出< / h4 >
< ul >
< li > 请求级任务:用 < code > context< / code > 取消< / li >
< li > 后台常驻任务:用 < code > done< / code > channel 或 < code > Stop()< / code > 方法< / li >
< li > 一次性任务:< code > WaitGroup< / code > / < code > errgroup< / code > 收敛< / li >
< / ul >
< / div >
< div class = "card" >
< h4 > 出口是否唯一< / h4 >
< ul >
< li > 多个 < code > return< / code > 时用 < code > defer cancel()< / code > < / li >
< li > 不要只靠「对面会关 channel」这种假设< / li >
< li > 发送方负责 < code > close< / code > ,接收方不要关< / li >
< / ul >
< / div >
2026-10-25 11:57:02 +08:00
< div class = "card" >
< h4 > 出错怎么传出来< / h4 >
< ul >
< li > < code > errgroup< / code > 只保证「拿到第一个错误」< / li >
< li > 其余任务靠 < code > ctx< / code > 被取消,不会自动停< / li >
< li > 错误要能对应到「哪个任务失败」< / li >
< / ul >
< / div >
2026-10-21 14:11:30 +08:00
< / div >
2026-10-25 11:57:02 +08:00
< p > 一个可直接套用的受控并发模板:用信号量限制并发度,用 < code > errgroup< / code > 收集第一个错误并取消其余任务。重点是 < code > ctx< / code > 一路传下去,任何阻塞调用都能被打断:< / p >
2026-10-21 14:11:30 +08:00
< pre data-lang = "go" data-name = "受控并发:并发度 + 取消 + 错误收敛" > func process(ctx context.Context, jobs []Job, limit int) error {
g, ctx := errgroup.WithContext(ctx)
sem := make(chan struct{}, limit) // 并发上限
for _, job := range jobs {
job := job
sem < - struct{}{} // 满了就阻塞,形成背压
g.Go(func() error {
defer func() { < -sem }()
return handle(ctx, job) // handle 内部所有阻塞调用都要看 ctx
})
}
return g.Wait()
}< / pre >
2026-10-25 11:57:02 +08:00
< p > < span class = "tag" > 代价< / span > 这段代码的价值不在语法,而在< strong > 背压< / strong > : < code > sem< / code > 满了以后,主循环会停下来等,而不是把任务无限塞进 goroutine。没有这个限制, QPS 一高就是几万个 goroutine 同时打下游,重试再放大一轮,故障面积立刻扩大。更完整的 worker pool 写法见 < a href = "13-puzzles.html#sec-13-8" > 13.8< / a > , context 取消的传播见 < a href = "11-context.html#sec-11-3" > 11.3< / a > 。< / p >
< p class = "take" > < b > 一句话:< / b > goroutine 不需要你创建得多优雅,只需要你退出得多明确。< / p >
< h2 id = "ch1-sum" > 全章回顾:三笔账一次结清< / h2 >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 这笔账< / th > < th > 便宜在哪< / th > < th > 代价< / th > < th > 翻车现场< / th > < / tr > < / thead >
< tbody >
< tr > < td > < b > 栈< / b > < / td > < td > 2 KB 起步,不够就翻倍复制,空闲时 GC 收缩< / td > < td > 地址会变、上限 1 GB、溢出不可 recover< / td > < td > 把栈地址存在堆上或 < code > uintptr< / code > 里 → 野指针< / td > < / tr >
< tr > < td > < b > 切换< / b > < / td > < td > 只存 SP/PC/BP, 始终用户态, 不陷内核< / td > < td > 只能在安全点切换< / td > < td > 纯计算死循环不吃抢占点 → 等异步抢占< / td > < / tr >
< tr > < td > < b > 阻塞< / b > < / td > < td > G 挂起时 M 继续跑别的 G< / td > < td > 系统调用会卡住 M, 要靠 handoff 止损< / td > < td > 没有退出路径 → goroutine 泄露 → OOM< / td > < / tr >
< / tbody >
< / table >
2026-10-21 14:11:30 +08:00
< / div >
2026-10-25 11:57:02 +08:00
< p > 把这一章压缩成一句话: goroutine 的便宜来自「用户态调度 + 小栈 + 少量现场」,代价是「运行时替你管阻塞和栈,但管不了你的退出逻辑」。下一章进入调度器内部,看 G、M、P 三者到底怎么协作。< / p >
2026-10-21 14:11:30 +08:00
< / article >
< nav class = "pager" >
< a class = "prev disabled" > < span class = "k" > ← 上一章< / span > < span class = "v" > 没有更多了< / span > < / a >
< a class = "next" href = "02-gmp.html" > < span class = "k" > 下一章 →< / span > < span class = "v" > 第 2 章 · GMP 调度器: Go 如何把十万个 goroutine 跑起来< / span > < / a >
< / nav >
< p class = "foot" >
Go 八股 · 第 1 章 从进程到 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 >