content(go): 新增 Go 八股知识库(14 章 126 小节 151 段代码),登记门户

This commit is contained in:
2026-10-21 14:11:30 +08:00
parent 1d10065ebd
commit d9629e87a8
173 changed files with 19891 additions and 1 deletions

View File

@@ -0,0 +1,364 @@
<!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>第 11 章 context:取消、超时与 goroutine 泄露防治 · Go 八股知识库</title>
<meta name="description" content="从 context 接口的四个方法讲到 cancelCtx、timerCtx、valueCtx 的实现,拆解取消信号如何沿树传播、超时预算怎么分配、WithValue 的边界,并给出六种 goroutine 泄露场景与检测手段。">
<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>第 11 章</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><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><span class="toc-a active" aria-current="page"><i class="cn">11</i>context:取消、超时与 goroutine 泄露防治</span><div class="subnav current"><a class="toc-a lv3" href="#sec-11-1">11.1 为什么需要 context</a><a class="toc-a lv3" href="#sec-11-2">11.2 四个实现:emptyCtx、cancelCtx、timerCtx、valueCtx</a><a class="toc-a lv3" href="#sec-11-3">11.3 取消如何沿树传播</a><a class="toc-a lv3" href="#sec-11-4">11.4 超时与截止时间</a><a class="toc-a lv3" href="#sec-11-5">11.5 WithValue 的边界</a><a class="toc-a lv3" href="#sec-11-6">11.6 使用规范:七条硬规则</a><a class="toc-a lv3" href="#sec-11-7">11.7 goroutine 泄露的六种场景</a><a class="toc-a lv3" href="#sec-11-8">11.8 检测与防治</a><a class="toc-a lv3" href="#sec-11-9">11.9 超时串联实战</a></div><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">11</b> / 14 章</span>
</p>
<h2 id="ch11"><span class="n">11</span>context:取消、超时与 goroutine 泄露防治</h2>
<div class="lead">
<b>这一章解决什么:</b>context 是 Go 里最容易被「用对一半」的标准库:知道要传 <code>ctx</code>,
却说不清取消信号怎么走、超时预算怎么分、<code>WithValue</code> 该不该用。
这一章把 context 拆成四件事:<strong>取消树、超时定时器、值查找链、泄露治理</strong>。
读完你要能回答:为什么 <code>cancel()</code> 必须调用、<code>context.Background()</code> 和 <code>TODO()</code> 有什么区别、
以及线上 goroutine 数只涨不跌时该从哪里查。
</div>
<h3 id="sec-11-1">11.1 为什么需要 context</h3>
<p>先看一个真实故障:网关设置了 500ms 超时,请求返回 504,但下游服务还在跑,
CPU 被打满,日志里同一个 trace 十分钟后仍在打印。根因不是超时没生效,而是
<strong>取消信号没有传下去</strong>:handler 返回了,它启动的 goroutine 和发起的 RPC 仍在按自己的节奏执行。</p>
<p>并发程序里,「停止」比「启动」难。一个请求可能派生多个 goroutine、多层 RPC、数据库查询和缓存访问,
调用方放弃等待时,需要有一种机制把「不用再做了」这个事实广播给整棵调用树。
context 就是标准库给出的答案:它是一棵<strong>只读的树</strong>,父节点取消会级联取消所有子节点,
同时还携带一个截止时间和少量请求级数据。</p>
<div class="tablewrap">
<table>
<thead><tr><th>需求</th><th>context 提供的能力</th><th>没有它时的替代方案与问题</th></tr></thead>
<tbody>
<tr><td>取消传播</td><td><code>Done()</code> 返回只读 channel,关闭即广播</td><td>自己传 <code>done chan struct{}</code>,跨 API 边界无法统一</td></tr>
<tr><td>超时控制</td><td><code>Deadline()</code> + <code>WithTimeout</code></td><td>每个下游各自 <code>time.After</code>,预算无法逐层扣减</td></tr>
<tr><td>请求级数据</td><td><code>Value(key)</code></td><td>全局 map 或参数透传,污染函数签名、并发不安全</td></tr>
<tr><td>跨服务传递</td><td>deadline 可编码进 RPC 头(如 gRPC 的 <code>grpc-timeout</code>)</td><td>各框架自定义协议,语义不一致</td></tr>
</tbody>
</table>
</div>
<p>context 在 Go 1.7 进入标准库,之前是 <code>golang.org/x/net/context</code>。
它的接口只有四个方法,刻意保持极小:</p>
<pre data-lang="go" data-name="context.Context">type Context interface {
Deadline() (deadline time.Time, ok bool)
Done() &lt;-chan struct{}
Err() error
Value(key any) any
}</pre>
<p>四个方法对应四种能力,合起来只有一条约定:<mark>Done 关闭后,Err 必须非 nil</mark>。
所有实现都围绕这条约定展开。</p>
<h3 id="sec-11-2">11.2 四个实现:emptyCtx、cancelCtx、timerCtx、valueCtx</h3>
<p>标准库没有用一个大而全的结构体,而是用四个小类型组合成一棵树。每个节点的 <code>Context</code> 字段
指向父节点,形成单向链;取消从上往下传播,值查找从下往上回溯。</p>
<div class="tablewrap">
<table>
<thead><tr><th>类型</th><th>创建方式</th><th>额外字段</th><th>职责</th></tr></thead>
<tbody>
<tr><td><code>emptyCtx</code></td><td><code>Background()</code> / <code>TODO()</code></td><td>无</td><td>树根,永不取消、无 deadline、无值</td></tr>
<tr><td><code>cancelCtx</code></td><td><code>WithCancel</code> / <code>WithCancelCause</code></td><td><code>done</code>、<code>children</code>、<code>err</code>、<code>cause</code></td><td>维护子节点集合,取消时关闭 done 并递归取消子节点</td></tr>
<tr><td><code>timerCtx</code></td><td><code>WithDeadline</code> / <code>WithTimeout</code></td><td>内嵌 <code>cancelCtx</code>、<code>timer</code>、<code>deadline</code></td><td>到期自动调用 cancel,错误为 <code>DeadlineExceeded</code></td></tr>
<tr><td><code>valueCtx</code></td><td><code>WithValue</code></td><td><code>key</code>、<code>val</code></td><td>只做值查找,不参与取消</td></tr>
</tbody>
</table>
</div>
<p>Go 1.21 之后,<code>Background()</code> 和 <code>TODO()</code> 返回的不再是同一个 <code>emptyCtx</code> 值,
而是 <code>backgroundCtx</code> 与 <code>todoCtx</code> 两个空结构体,只是为了让 <code>go vet</code> 和调试更容易区分。
两者行为完全一样:<code>Done()</code> 返回 nil channel(永久阻塞),<code>Err()</code> 返回 nil。
语义差别只在约定:<code>Background</code> 用于 main、初始化、测试;<code>TODO</code> 表示「还没想好该用哪个」,是待办标记。</p>
<pre data-lang="go" data-name="cancelCtx 的关键字段">type cancelCtx struct {
Context
mu sync.Mutex
done atomic.Value // chan struct{}
children map[canceler]struct{}
err error // 只在 Done 关闭后写
cause error // Go 1.20 起,WithCancelCause 使用
}</pre>
<p><code>done</code> 用 <code>atomic.Value</code> 而不是普通字段,是为了让 <code>Done()</code> 在无锁情况下快速返回;
首次调用时才 <code>make</code> 出 channel 并存入。<code>children</code> 用 map 而不是切片,是为了取消时能 O(1) 删除节点、避免重复取消。</p>
<div class="box tip">
<span class="bt">面试追问:Done 为什么是只读 channel</span>
<p>只读方向(<code>&lt;-chan struct{}</code>)限制调用方只能接收,不能发送或关闭。
关闭动作必须由 context 内部完成,否则调用方一 <code>close</code>,父节点和兄弟节点都会收到假的取消信号。</p>
</div>
<h3 id="sec-11-3">11.3 取消如何沿树传播</h3>
<p>创建子节点时,<code>propagateCancel</code> 会沿着父链向上找最近的可取消节点,把自己注册进它的 <code>children</code>。
注册成功后,父节点取消时遍历 children 逐个调用 <code>cancel</code>,就完成了级联。</p>
<pre data-lang="go" data-name="取消树的建立与传播">ctx, cancel := context.WithCancel(context.Background())
defer cancel() // 无论如何都要调用,防止泄露
child, cancelChild := context.WithCancel(ctx)
defer cancelChild()
go func() {
&lt;-child.Done()
fmt.Println("child err:", child.Err()) // context.Canceled
}()
cancel() // 关闭 ctx.done,并级联关闭 child.done
time.Sleep(time.Millisecond)
fmt.Println("parent err:", ctx.Err()) // context.Canceled</pre>
<p><code>cancelCtx.cancel</code> 做四件事:关闭自己的 done channel、给 err 赋值、遍历并取消所有子节点、把自己从父节点 children 中删除。
删除这一步很关键,否则一个长期存活的父 context 会持有所有历史子节点,形成内存泄露。</p>
<p><code>Err()</code> 的取值只有三种:未取消时为 <code>nil</code>,主动取消为 <code>context.Canceled</code>,
超时为 <code>context.DeadlineExceeded</code>。<code>Canceled</code> 是一个哨兵错误,可以用 <code>errors.Is</code> 判断。
Go 1.20 增加了 <code>WithCancelCause</code> 和 <code>context.Cause(ctx)</code>,可以携带业务原因:</p>
<pre data-lang="go" data-name="WithCancelCause">ctx, cancel := context.WithCancelCause(context.Background())
cancel(fmt.Errorf("order %d cancelled by user", 42))
fmt.Println(errors.Is(ctx.Err(), context.Canceled)) // true
fmt.Println(context.Cause(ctx)) // order 42 cancelled by user</pre>
<div class="box warn">
<span class="bt">容易答错的点:Canceled 与 DeadlineExceeded 不相等</span>
<p>超时取消的 <code>Err()</code> 是 <code>DeadlineExceeded</code>,不是 <code>Canceled</code>。
如果要统一判断「是不是被取消」,用 <code>ctx.Err() != nil</code>,不要只比较 <code>Canceled</code>。</p>
</div>
<h3 id="sec-11-4">11.4 超时与截止时间</h3>
<p><code>WithTimeout(parent, d)</code> 等价于 <code>WithDeadline(parent, time.Now().Add(d))</code>。
它创建 <code>timerCtx</code>,起一个 <code>time.AfterFunc</code>,到期时调用 <code>cancel(true, DeadlineExceeded, ...)</code>。
如果提前手动 cancel,会把定时器 <code>Stop</code> 掉,避免定时器泄露。</p>
<pre data-lang="go" data-name="给下游调用设置超时">func fetch(ctx context.Context, url string) ([]byte, error) {
ctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
defer cancel() // 即使请求很快返回,也要释放定时器
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("fetch %s: %w", url, err) // 保留 DeadlineExceeded
}
defer resp.Body.Close()
return io.ReadAll(resp.Body)
}</pre>
<p>超时预算要逐层扣减,而不是每层都设一个固定值。假设入口总预算 500ms,鉴权 50ms、查缓存 50ms、
查数据库 200ms、调下游 150ms,那么每层应该基于父 context 的剩余时间再设上限,
否则子层各自 500ms,父层早已超时,子层还在白干。</p>
<div class="box note">
<span class="bt">跨进程传递</span>
<p>gRPC 会把 deadline 编码进 <code>grpc-timeout</code> 头,服务端解析后作为父 context 的截止时间;
HTTP 没有标准头,通常在网关层统一注入 <code>X-Request-Timeout</code> 或直接在服务端按接口配置。
「超时能不能传下去」是区分「会用 context」和「只传了 ctx 参数」的关键。</p>
</div>
<h3 id="sec-11-5">11.5 WithValue 的边界</h3>
<p><code>WithValue</code> 只适合放<strong>请求级、不可变、小体积</strong>的元数据:trace id、用户身份、
租户 id、灰度标记。不适合放数据库连接、logger、配置对象,更不适合当可选参数用。</p>
<pre data-lang="go" data-name="用私有类型做 key">type ctxKey struct{ name string }
var (
traceKey = ctxKey{"trace_id"}
userKey = ctxKey{"user_id"}
)
func withTrace(ctx context.Context, id string) context.Context {
return context.WithValue(ctx, traceKey, id)
}
func traceID(ctx context.Context) string {
id, _ := ctx.Value(traceKey).(string)
return id
}</pre>
<p>key 必须用自定义的未导出类型,不能用字符串字面量。字符串 key 容易和别的包撞车,
一旦撞车就是静默覆盖,排查成本极高。查找是沿父链一路向上,复杂度 O(深度),
所以不要在一棵深树上挂几十个值。</p>
<div class="box danger">
<span class="bt">三个常见误用</span>
<p>① 把 <code>*sql.DB</code>、<code>*zap.Logger</code> 塞进 context——这些应该是构造参数;
② 用 context 传可变对象,多个 goroutine 并发改,数据竞争;
③ 把 context 存进结构体字段长期持有,导致请求结束后值还被引用,泄露内存。</p>
</div>
<h3 id="sec-11-6">11.6 使用规范:七条硬规则</h3>
<ol class="steps">
<li><b>第一个参数。</b><code>func Do(ctx context.Context, ...)</code>,命名统一为 <code>ctx</code>,不要叫 <code>c</code> 或 <code>context</code>。</li>
<li><b>不要传 nil。</b>不确定时传 <code>context.TODO()</code>,nil 会在调用 <code>Done()</code> 时直接 panic。</li>
<li><b>谁创建谁取消。</b>拿到 <code>cancel</code> 的函数必须调用它,惯例是紧接着写 <code>defer cancel()</code>。</li>
<li><b>不要存字段。</b>除构造函数外,不把 ctx 放进结构体;需要跨方法传递时显式传参。</li>
<li><b>只在请求范围用。</b>不要用 context 做全局配置、依赖注入或长期后台任务的生命周期。</li>
<li><b>下游必须响应。</b>收到 ctx 后要把它传给下一层,并在阻塞点用 <code>select</code> 监听 <code>Done()</code>。</li>
<li><b>不要自定义 Context 实现。</b>标准库的类型已经覆盖全部场景,自定义实现容易破坏取消语义。</li>
</ol>
<p><code>go vet</code> 的 <code>lostcancel</code> 检查能发现「创建了 cancel 但没用」的代码,
这是 CI 里成本最低的一道防线。</p>
<h3 id="sec-11-7">11.7 goroutine 泄露的六种场景</h3>
<p>goroutine 泄露的本质是:某个 goroutine 永久阻塞在一个永远不会就绪的操作上,
它持有的栈、变量、channel 引用都无法回收。压测时表现为 <code>runtime.NumGoroutine()</code> 只涨不跌,
最终 OOM 或调度器过载。</p>
<div class="tablewrap">
<table>
<thead><tr><th>场景</th><th>阻塞点</th><th>修法</th></tr></thead>
<tbody>
<tr><td>向无缓冲 channel 发送,无人接收</td><td><code>ch &lt;- v</code></td><td>接收方退出时用 <code>select</code> 监听 <code>ctx.Done()</code>;或改用带缓冲 channel</td></tr>
<tr><td>从 channel 接收,无人发送</td><td><code>&lt;-ch</code></td><td>同上,加 <code>ctx.Done()</code> 分支或关闭 channel</td></tr>
<tr><td>操作 nil channel</td><td>永久阻塞</td><td>初始化 channel;不要声明后忘记 <code>make</code></td></tr>
<tr><td>等锁 / 等 WaitGroup</td><td><code>mu.Lock()</code>、<code>wg.Wait()</code></td><td>减少临界区、确保 <code>Done</code> 一定被调用;等待类操作尽量支持 ctx</td></tr>
<tr><td>创建了 <code>WithCancel</code> 却不 cancel</td><td>子节点常驻父节点 children</td><td><code>defer cancel()</code>,即使函数立即返回</td></tr>
<tr><td><code>time.Ticker</code> 未 Stop</td><td>定时器与 goroutine 常驻</td><td><code>defer ticker.Stop()</code>;一次性定时用 <code>time.After</code> 并注意版本差异</td></tr>
</tbody>
</table>
</div>
<pre data-lang="go" data-name="典型泄露与修复">// 泄露:消费者提前返回,生产者永远阻塞在发送上
func leak() {
ch := make(chan int)
go func() {
for i := 0; ; i++ {
ch &lt;- i // 没有接收者时永久阻塞
}
}()
// 函数返回,ch 无人接收,上面的 goroutine 永不退出
}
// 修复:用 ctx 提供退出路径
func fixed(ctx context.Context) {
ch := make(chan int)
go func() {
defer close(ch)
for i := 0; ; i++ {
select {
case ch &lt;- i:
case &lt;-ctx.Done():
return
}
}
}()
for v := range ch {
if v &gt; 3 {
return // 返回前应 cancel 父 ctx,生产者才能退出
}
}
}</pre>
<h3 id="sec-11-8">11.8 检测与防治</h3>
<p>线上排查分三步:先看数量趋势,再看栈,最后定位到具体函数。</p>
<pre data-lang="bash" data-name="goroutine 排查命令"># 1. 暴露 pprof(生产环境建议只在内网端口开)
import _ "net/http/pprof"
go func() { http.ListenAndServe("127.0.0.1:6060", nil) }()
# 2. 看数量与栈摘要
go tool pprof http://127.0.0.1:6060/debug/pprof/goroutine?debug=1
# 3. 看完整栈,定位阻塞点
curl 'http://127.0.0.1:6060/debug/pprof/goroutine?debug=2' | head -100
# 4. 对比两个时间点的栈,找出持续存在的调用
go tool pprof -base old.pb new.pb</pre>
<p>单测里可以用 <code>go.uber.org/goleak</code> 在 <code>TestMain</code> 中断言没有残留 goroutine:</p>
<pre data-lang="go" data-name="goleak 断言">func TestMain(m *testing.M) {
goleak.VerifyTestMain(m)
}
func TestWorker(t *testing.T) {
defer goleak.VerifyNone(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
startWorker(ctx)
}</pre>
<p>防治的核心不是「检测」,而是<strong>给每个 goroutine 设计退出路径</strong>:
启动时就想清楚谁会关 channel、谁会 cancel context、阻塞点有没有 <code>select</code> 兜底。</p>
<h3 id="sec-11-9">11.9 超时串联实战</h3>
<p>把前面的点串成一个真实链路:HTTP 入口 500ms 总预算,服务层并行查缓存和数据库,
任一失败就取消另一个,最后统一映射错误。</p>
<pre data-lang="go" data-name="带预算的并行调用">func (s *Service) Get(ctx context.Context, id int64) (*Order, error) {
ctx, cancel := context.WithTimeout(ctx, 500*time.Millisecond)
defer cancel()
g, ctx := errgroup.WithContext(ctx)
var order *Order
var cached bool
g.Go(func() error {
o, err := s.cache.Get(ctx, id)
if err == nil {
order, cached = o, true
}
return nil // 缓存未命中不算错误
})
g.Go(func() error {
o, err := s.repo.Get(ctx, id)
if err != nil {
return fmt.Errorf("repo.Get: %w", err)
}
order = o
return nil
})
if err := g.Wait(); err != nil &amp;&amp; !cached {
if errors.Is(err, context.DeadlineExceeded) {
return nil, status.Error(codes.DeadlineExceeded, "query timeout")
}
return nil, err
}
return order, nil
}</pre>
<p><code>errgroup.WithContext</code> 在第一个 goroutine 返回错误时取消派生 context,
另一个请求会收到 <code>context.Canceled</code> 并尽快退出,避免「一个失败、另一个还在跑」。
注意:<code>cancel</code> 仍然要 <code>defer</code>,<code>errgroup</code> 的取消不会释放父 context 的定时器。</p>
<div class="box case">
<span class="bt">一个排查案例</span>
<p>某服务 P99 从 80ms 涨到 2s,<code>NumGoroutine</code> 每小时涨 3000。pprof 显示大量 goroutine 卡在
<code>chan send</code>,栈指向一个日志异步上报函数:它的 channel 满了之后直接阻塞发送。
修法是把「满了就丢」写进 <code>select</code> 的 <code>default</code> 分支,并加 ctx 退出。
这类问题的共同点是:<strong>没有退出路径的阻塞写</strong>。</p>
</div>
<div class="box tip">
<span class="bt">面试怎么答</span>
<p>「context 是一棵取消树,父取消级联子,Done 关闭即广播;超时用 timerCtx,到期自动 cancel 并置
DeadlineExceeded;WithValue 只放请求级元数据。使用上记住三条:第一个参数、defer cancel、下游要响应。
泄露的本质是 goroutine 卡在无退出路径的阻塞上,排查用 pprof goroutine,防治靠启动时就设计好退出信号。」</p>
</div>
</article>
<nav class="pager">
<a class="prev" href="10-sync.html"><span class="k">← 上一章</span><span class="v">第 10 章 · 锁与同步原语:从 Mutex 到 singleflight</span></a>
<a class="next" href="12-interface.html"><span class="k">下一章 →</span><span class="v">第 12 章 · 接口:隐式契约与运行时表示</span></a>
</nav>
<p class="foot">
Go 八股 · 第 11 章 context:取消、超时与 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>