Files
materials/knowledge/Go/11-context.html

554 lines
47 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!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="box ok">
<span class="bt">面试直答 · 30 秒版</span>
<p>context 用来在调用链上传递取消信号、超时和少量元数据。它是一棵取消树:父 context 被取消,所有子 context 都会跟着取消,靠 Done() 返回的 channel 关闭来广播。四个构造:Background 和 TODO 是根;WithCancel 手动取消;WithTimeout / WithDeadline 定时取消;WithValue 传请求级数据。使用上记四条:作为函数的第一个参数;不要存进结构体;拿到 cancel 必须 defer cancel(),不然定时器和子节点会泄露;下游的阻塞操作要监听 ctx.Done()。goroutine 泄露的本质,就是它卡在一个没有退出路径的阻塞上。</p>
<ul>
<li>超时到期返回 DeadlineExceeded,主动取消返回 Canceled,统一判断用 ctx.Err() != nil。</li>
<li>WithValue 只放 trace id、用户身份这类请求级元数据,别拿来传业务参数。</li>
<li>查泄露用 pprof 的 goroutine 视图,看堆栈到底卡在哪一行。</li>
</ul>
</div>
<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>
<h4>读之前:5 个词</h4>
<div class="tablewrap">
<table>
<thead><tr><th>术语</th><th>一句话</th><th>在哪节</th></tr></thead>
<tbody>
<tr><td>取消树</td><td>父被取消时,登记过的子节点跟着收到信号</td><td>11.3</td></tr>
<tr><td>Done channel</td><td>关闭即广播的只读 channel,唯一的取消信号</td><td>11.2</td></tr>
<tr><td>deadline</td><td>绝对时刻;超时只是它的语法糖</td><td>11.4</td></tr>
<tr><td>valueCtx</td><td>沿父链向上查找值的链表节点</td><td>11.5</td></tr>
<tr><td>goroutine 泄露</td><td>永久阻塞、没有退出路径,栈和引用都收不回</td><td>11.7</td></tr>
</tbody>
</table>
</div>
<div class="box tip">
<span class="bt">怎么读这一章</span>
<p>11.1–11.2 是地基,讲清接口为什么只有四个方法;11.3–11.5 是三个机制各自怎么实现;11.6 是纪律清单,面试最常追问;11.7–11.9 是事故现场:怎么泄露、怎么查出来、怎么在一条真实链路上把预算串起来。赶时间的话,先读每节的「一句话」,再读 11.7 那张六场景表。</p>
</div>
<h3 id="sec-11-1">11.1 为什么需要 context</h3>
<p><span class="tag">现象</span>网关给入口配了 500ms 超时,客户端准时收到 504;可下游服务的 CPU 还在打满,日志里同一个 trace 十分钟后仍在刷。同时 <code>runtime.NumGoroutine()</code> 从 1200 爬到 9000,不回落。</p>
<p><span class="tag">机制</span>超时确实生效了,但它只作用在「网关等不等」这一件事上。网关启动的那些 goroutine、发起的 RPC、排队中的查询,没有谁被告知「这个结果没人要了」。并发里「停止」比「启动」难,因为一次请求会派生出一棵树,需要一个信号同时通知整棵树。</p>
<p>context 就是这个信号:一棵<strong>只读的树</strong>,父节点取消会级联取消所有子节点,同时还携带一个截止时间和少量请求级数据。它解决的从来不是「怎么杀死一个 goroutine」,而是「怎么让整棵树知道该停了」。</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>接口刻意保持极小,只有四个方法(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>
<p><span class="tag">代价</span>代价先落在签名上:任何想被取消的函数都得接受一个它并不理解的参数,于是从 handler 到底层查询,整条链路的 API 都多了一个位置。其次是控制反转——调用方以为自己在「停止」,实际只是关掉一个 channel,没监听的人照旧跑完。</p>
<p class="take"><b>一句话:</b>context 不是 goroutine 的 kill 信号,只是一棵广播「别再做了」的树;接不接这个信号,取决于每个阻塞点有没有在听。</p>
<h3 id="sec-11-2">11.2 四个实现:emptyCtx、cancelCtx、timerCtx、valueCtx</h3>
<p><span class="tag">现象</span>打印 <code>context.Background()</code> 的类型,Go 1.21 起是 <code>context.backgroundCtx</code>,1.20 及以前是 <code>*context.emptyCtx</code>。对同一个根调三个方法,返回全是空:Done 给 nil,Err 给 nil,Value 也是 nil,可它照样是合法的树根。</p>
<p><span class="tag">机制</span>标准库没有用一个大而全的结构体,而是四个小类型,每个节点带一个指向父节点的字段,串成一条单链。逻辑上看到的是一棵树,物理上只有「父指针」这一个方向:取消顺着它往下走,值查找逆着它往上走。</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>取消类的节点比根多带四样东西:</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 atomic.Value // 首次 cancel 时原子写入;Err() 无锁读
cause error // Go 1.20 起,WithCancelCause 使用
}</pre>
<p>done 用原子容器而不是普通字段,是为了让 Done 能无锁快速返回:第一次调用时才创建 channel 并存入,之后所有调用共享同一个。children 用 map 而不是切片,是为了注册和摘除都是常数时间,也顺手去重。</p>
<p>四类节点摆在一起,形状就很清楚:只有取消类节点在链上「挂东西」,值节点只是往链上贴一对键值,定时节点则在取消节点上加一条时间。</p>
<figure class="figure">
<svg viewBox="0 0 720 300" role="img" aria-label="根、cancelCtx、valueCtx 串成一条单链,取消信号向下传、值查找向上回溯">
<defs>
<marker id="ar11a" markerWidth="9" markerHeight="9" refX="7" refY="3" orient="auto">
<path d="M0,0 L7,3 L0,6 Z" style="fill:var(--brand)"/>
</marker>
</defs>
<text x="24" y="28" font-size="12.5" style="fill:var(--muted)">逻辑上是一棵树,物理上每个节点只有一个指向父的字段</text>
<rect x="30" y="78" width="180" height="54" rx="9" style="fill:var(--card);stroke:var(--line)"/>
<text x="120" y="102" text-anchor="middle" font-size="13" font-weight="700" style="fill:var(--ink)">根(空结构体)</text>
<text x="120" y="122" text-anchor="middle" font-size="11.5" style="fill:var(--muted)">永不取消,Done 为 nil</text>
<rect x="270" y="78" width="180" height="54" rx="9" style="fill:var(--brand-soft);stroke:var(--brand)"/>
<text x="360" y="102" text-anchor="middle" font-size="13" font-weight="700" style="fill:var(--brand-ink)">cancelCtx</text>
<text x="360" y="122" text-anchor="middle" font-size="11.5" style="fill:var(--ink)">done / children / err</text>
<rect x="510" y="78" width="180" height="54" rx="9" style="fill:var(--card);stroke:var(--line)"/>
<text x="600" y="102" text-anchor="middle" font-size="13" font-weight="700" style="fill:var(--ink)">valueCtx</text>
<text x="600" y="122" text-anchor="middle" font-size="11.5" style="fill:var(--muted)">key / val,不参与取消</text>
<path d="M510,105 L456,105" style="fill:none;stroke:var(--brand);stroke-width:1.6" marker-end="url(#ar11a)"/>
<path d="M270,105 L216,105" style="fill:none;stroke:var(--brand);stroke-width:1.6" marker-end="url(#ar11a)"/>
<text x="483" y="152" text-anchor="middle" font-size="11.5" style="fill:var(--brand-ink)">Context 字段</text>
<text x="243" y="152" text-anchor="middle" font-size="11.5" style="fill:var(--brand-ink)">Context 字段</text>
<text x="360" y="200" text-anchor="middle" font-size="12.5" style="fill:var(--warn)">取消:父节点关闭 done,递归 cancel 每个子节点</text>
<path d="M96,218 L624,218" style="fill:none;stroke:var(--brand);stroke-width:1.6" marker-end="url(#ar11a)"/>
<text x="360" y="252" text-anchor="middle" font-size="12.5" style="fill:var(--ok)">查找:Value(key) 逐层向上比较 key,一直走到根</text>
<path d="M624,270 L96,270" style="fill:none;stroke:var(--brand);stroke-width:1.6" marker-end="url(#ar11a)"/>
</svg>
<div class="figcap"><b>图 1</b> · 同一条链两个方向:取消向下级联,值查找向上回溯</div>
</figure>
<div class="box tip">
<span class="bt">面试追问:Done 为什么是只读 channel</span>
<p>只读方向(<code>&lt;-chan struct{}</code>)限制调用方只能接收,不能发送或关闭。关闭动作必须由 context 内部完成,否则调用方一 <code>close</code>,父节点和兄弟节点都会收到假的取消信号。</p>
</div>
<p><span class="tag">代价</span>每个取消节点至少多一把锁、一个 map 头和一个原子槽;每贴一层值只多两个字段,但查找要多跳一层指针。真正贵的是深度:一百层嵌套的链上取一个值,要走一百次接口比较。</p>
<p class="take"><b>一句话:</b>四种类型串成一条单链,取消向下传、查找向上走;「树」只是逻辑概念,物理结构里每个节点只认自己的父。</p>
<div class="box warn">
<span class="bt">可跳过 · 1.21 才把根拆成两个类型</span>
<p><span class="tag s">可跳过</span>1.21 起标准库拆出 backgroundCtx 和 todoCtx 两个空结构体,行为完全一致,只是让调试和静态检查能一眼看出「这里是不是忘了换成真正的 ctx」。语义差别只有约定:根用于 main、初始化、测试;待办标记表示「还没想好该用哪个」。</p>
</div>
<h3 id="sec-11-3">11.3 取消如何沿树传播</h3>
<p><span class="tag">现象</span>建一条 root → A → B 的链,只对 root 调一次 cancel:A 和 B 的 Err 立刻都变成 Canceled,三条 Done 同时可读,等在三个 channel 上的 goroutine 一起醒来。</p>
<p><span class="tag">机制</span>「谁通知谁」在创建子节点的瞬间就定好了:propagateCancel 沿父链向上找最近一个可取消的节点,把子节点自己塞进它的 children 集合。之后父节点取消,只需遍历 children 逐个调 cancel,级联就完成了。</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>每次取消做四件事:写 err、关自己的 done、遍历 children 递归取消、按需把自己从父节点的 children 里摘掉。第四件不是无条件的——只有自己主动取消(调用 cancel 函数或超时定时器到点)时才传 true(context.go:576-578),父节点级联下来时一律传 false(child.cancel(false, ...))。理由是整棵子树都要丢,逐个摘除只是白花时间。</p>
<figure class="figure">
<svg viewBox="0 0 720 340" role="img" aria-label="取消从根节点向下级联到 A、B、C;A 被手动取消时还会把自己从父节点的 children 集合里摘掉">
<defs>
<marker id="ar11b" markerWidth="9" markerHeight="9" refX="7" refY="3" orient="auto">
<path d="M0,0 L7,3 L0,6 Z" style="fill:var(--brand)"/>
</marker>
<marker id="ar11b2" markerWidth="9" markerHeight="9" refX="7" refY="3" orient="auto">
<path d="M0,0 L7,3 L0,6 Z" style="fill:var(--danger)"/>
</marker>
</defs>
<rect x="270" y="30" width="200" height="56" rx="9" style="fill:var(--brand-soft);stroke:var(--brand)"/>
<text x="370" y="54" text-anchor="middle" font-size="13" font-weight="700" style="fill:var(--brand-ink)">root(被取消)</text>
<text x="370" y="74" text-anchor="middle" font-size="11.5" style="fill:var(--ink)">children{A, B}</text>
<rect x="78" y="160" width="170" height="52" rx="9" style="fill:var(--card);stroke:var(--line)"/>
<text x="163" y="182" text-anchor="middle" font-size="13" font-weight="700" style="fill:var(--ink)">A</text>
<text x="163" y="200" text-anchor="middle" font-size="11.5" style="fill:var(--muted)">done 已关闭</text>
<rect x="330" y="160" width="170" height="52" rx="9" style="fill:var(--card);stroke:var(--line)"/>
<text x="415" y="182" text-anchor="middle" font-size="13" font-weight="700" style="fill:var(--ink)">B</text>
<text x="415" y="200" text-anchor="middle" font-size="11.5" style="fill:var(--muted)">done 已关闭</text>
<rect x="330" y="266" width="170" height="52" rx="9" style="fill:var(--card);stroke:var(--line)"/>
<text x="415" y="288" text-anchor="middle" font-size="13" font-weight="700" style="fill:var(--ink)">C(B 的孩子)</text>
<text x="415" y="306" text-anchor="middle" font-size="11.5" style="fill:var(--muted)">done 已关闭</text>
<path d="M300,86 C240,102 194,124 172,156" style="fill:none;stroke:var(--brand);stroke-width:1.6" marker-end="url(#ar11b)"/>
<path d="M400,86 C408,112 413,132 415,156" style="fill:none;stroke:var(--brand);stroke-width:1.6" marker-end="url(#ar11b)"/>
<path d="M415,212 L415,262" style="fill:none;stroke:var(--brand);stroke-width:1.6" marker-end="url(#ar11b)"/>
<text x="452" y="242" text-anchor="middle" font-size="11" style="fill:var(--muted)">cancel(false)</text>
<path d="M78,186 C34,186 34,62 264,58" style="fill:none;stroke:var(--danger);stroke-width:1.4;stroke-dasharray:5 4" marker-end="url(#ar11b2)"/>
<text x="54" y="142" font-size="11.5" style="fill:var(--danger)">虚线=摘除自己</text>
</svg>
<div class="figcap"><b>图 2</b> · 向下是级联取消,向上只有一条虚线:把自己从父节点的 children 里摘掉</div>
</figure>
<p>摘除对「手动取消、父节点还长命」的场景很关键:不摘,父节点的 map 会一直挂着这个已经死掉的子节点,直到父节点自己被取消。</p>
<p>Err 只有三种取值:未取消是 nil,主动取消是 Canceled,超时是 DeadlineExceeded。两个哨兵错误用 errors.Is 判断。Go 1.20 又加了带原因的取消,可以把业务原因一并带上:</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">易错点 · cancel 只是关 channel,不会杀 goroutine</span>
<p>很多人以为父 ctx 一取消,子 goroutine 就被结束掉。实际它只让 select 里一个分支就绪:<b>没监听 Done 的 goroutine 照样跑完</b>。验证很简单——起一个死循环 goroutine,cancel 之后 NumGoroutine 不会下降。</p>
</div>
<p><span class="tag">代价</span>children 是 map 加互斥锁,注册和摘除都要抢锁;级联是同步递归,在调 cancel 的那个 goroutine 上一次性做完,深树上一次取消就是 N 次函数调用加 N 次 close;close 又会把全部等待者同时唤醒,下游一起被放出来抢同一把锁。</p>
<p class="take"><b>一句话:</b>级联不是遍历出来的,是建节点时就登记好的:向上找祖先注册,向下沿 children 递归;代价全部压在调用 cancel 的那一个 goroutine 上。</p>
<h3 id="sec-11-4">11.4 超时与截止时间</h3>
<p><span class="tag">现象</span>同一个 ctx,在入口打印「还剩 500ms」,传到第三层再打印只剩 180ms。<b>超时是绝对时刻,不是每层重新计的 500ms</b>。反过来,如果第三层打印出来还是 500ms,基本可以断定:ctx 传丢了,传下去的是新根。</p>
<p><span class="tag">机制</span>带超时的构造只是「截止时间」的语法糖:参数是相对时长,进去立刻换算成绝对时刻。它在取消节点上加一个定时器和一条截止时间,到点由 runtime 的定时器堆唤醒回调,回调里调 cancel 并写入 DeadlineExceeded。</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>还有一个能省掉一堆困惑的细节:如果父 ctx 的截止时间本来就比新设的更早,构造会直接退化成不带定时器的取消节点——预算自动继承,子层不可能比父层活得更久。</p>
<pre data-lang="go" data-name="context.go:父的 deadline 更早时不再起定时器">func WithDeadlineCause(parent Context, d time.Time, cause error) (Context, CancelFunc) {
if cur, ok := parent.Deadline(); ok &amp;&amp; cur.Before(d) {
return WithCancel(parent) // 已有更紧的预算,继承即可
}
// 否则才建 timerCtx 并起定时器(Go 1.21 起 WithDeadline 只是转调这里)
}</pre>
<figure class="figure">
<svg viewBox="0 0 720 300" role="img" aria-label="时间轴对比:已花 300ms 之后,库里自己再算 500ms 会拖到 800ms;改用父 context 的剩余 200ms,正好在 500ms 收口">
<defs>
<marker id="ar11c" markerWidth="9" markerHeight="9" refX="7" refY="3" orient="auto">
<path d="M0,0 L7,3 L0,6 Z" style="fill:var(--muted)"/>
</marker>
</defs>
<text x="24" y="24" font-size="12.5" style="fill:var(--muted)">横轴:从请求进入网关开始计时(ms)</text>
<text x="390" y="38" text-anchor="middle" font-size="11.5" style="fill:var(--danger)">父 deadline = 500ms</text>
<line x1="390" y1="48" x2="390" y2="250" style="stroke:var(--danger);stroke-width:1.4;stroke-dasharray:5 4"/>
<text x="142" y="104" text-anchor="end" font-size="12" style="fill:var(--danger)">错:自带 500ms</text>
<rect x="150" y="84" width="144" height="30" style="fill:var(--brand-soft);stroke:var(--brand)"/>
<text x="222" y="104" text-anchor="middle" font-size="11" style="fill:var(--brand-ink)">已花 300ms</text>
<rect x="294" y="84" width="240" height="30" style="fill:var(--danger-bg);stroke:var(--danger)"/>
<text x="414" y="104" text-anchor="middle" font-size="11.5" style="fill:var(--danger)">再等 500ms(白干)</text>
<text x="142" y="190" text-anchor="end" font-size="12" style="fill:var(--ok)">对:用剩余</text>
<rect x="150" y="170" width="144" height="30" style="fill:var(--brand-soft);stroke:var(--brand)"/>
<text x="222" y="190" text-anchor="middle" font-size="11" style="fill:var(--brand-ink)">已花 300ms</text>
<rect x="294" y="170" width="96" height="30" style="fill:var(--ok-bg);stroke:var(--ok)"/>
<text x="342" y="190" text-anchor="middle" font-size="11" style="fill:var(--ink)">200ms</text>
<text x="396" y="190" font-size="11" style="fill:var(--muted)">到 500ms 收口</text>
<line x1="150" y1="250" x2="662" y2="250" style="stroke:var(--line);stroke-width:1.2" marker-end="url(#ar11c)"/>
<text x="150" y="268" text-anchor="middle" font-size="11" style="fill:var(--muted)">0</text>
<text x="294" y="268" text-anchor="middle" font-size="11" style="fill:var(--muted)">300</text>
<text x="390" y="268" text-anchor="middle" font-size="11" style="fill:var(--danger)">500</text>
<text x="630" y="268" text-anchor="middle" font-size="11" style="fill:var(--muted)">1000</text>
</svg>
<div class="figcap"><b>图 3</b> · 同样已花 300ms:库里自己再算 500ms 会拖到 800ms,白干 300ms;用父的剩余 200ms,正好 500ms 收口</div>
</figure>
<p>所以「逐层扣减」不是靠每层做减法的算术,而是靠<b>把父 ctx 一路传下去</b>:子层的截止时间自动取「父的和自己的更早者」。真正的坑是数据源不认 ctx——连接池的读超时、第三方 SDK 自带的固定超时,都是独立于 ctx 的第二个时钟,它们不会因为 ctx 到期就提前返回。</p>
<div class="box warn">
<span class="bt">易错点 · DeadlineExceeded 不等于 Canceled</span>
<p>超时取消时 Err 是 DeadlineExceeded,不是 Canceled,用 errors.Is 互相比较也不相等。要判断「是不是被取消了」,统一写 <code>ctx.Err() != nil</code>,别只跟 Canceled 比。</p>
</div>
<p><span class="tag">代价</span>每个带超时的节点都要向 runtime 登记一条定时器记录,提前返回就得靠 defer cancel 把它撤掉,否则一直挂到到期;定时器堆按 P 分片,增删只抢所在 P 的锁(runtime/time.go:130-134),高频短超时不会挤在一把全局锁上。</p>
<p class="take"><b>一句话:</b>超时是绝对时刻,父子取更早;「每层设 500ms」不等于每层都有 500ms,真正决定死活的是入口那一个 deadline。</p>
<div class="box note">
<span class="bt">跨进程传递</span>
<p>gRPC 会把 deadline 编码进 <code>grpc-timeout</code> 头,服务端解析后当成父 context 的截止时间;HTTP 没有标准头,通常在网关层注入 <code>X-Request-Timeout</code> 或在服务端按接口配置。这就是值过不了线、deadline 却能过线的原因。</p>
</div>
<h3 id="sec-11-5">11.5 WithValue 的边界</h3>
<p><span class="tag">现象</span>handler 里写进去的 trace id,下游函数读出来是空串。翻代码才发现中间某一层调了 <code>ctx = context.Background()</code>,把上面整条链截断了。值只在树上向下可见,中间断一层,下面就全断。</p>
<p><span class="tag">机制</span>valueCtx 只有三个字段:父 Context、key、val。Value 的实现就是一个循环——当前节点 key 相等就返回,不等就落到父节点,走到根还没命中就返回 nil。所以它是<b>链表查找,不是哈希表</b>。</p>
<p>只适合放<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 必须用自定义的未导出类型,不能用字符串字面量——两个包各写一个 <code>"user_id"</code> 就会静默撞车,后写的覆盖先写的,编译器一个警告都不给。查找沿父链一路向上,复杂度 O(深度),所以别在一棵深树上挂几十个值。</p>
<div class="box warn">
<span class="bt">易错点 · valueCtx 是链表不是哈希表</span>
<p>它的查找成本随链长线性增长,挂 5 个值和挂 50 个值在热路径上差一个数量级;字符串 key 撞车不报错、只覆盖,这两种问题都不会在编译期暴露,只能在 pprof 或线上 bug 里发现。</p>
</div>
<p><span class="tag">代价</span>每次取值都是一次链长×比较的遍历;值被树钉住——只要父 ctx 还活着,塞进去的对象(哪怕是几 MB 的响应体)就不能回收。更要命的是它诱惑人把可变对象传进来:多个 goroutine 并发改同一个 map,<code>go test -race</code> 直接报数据竞争。</p>
<p class="take"><b>一句话:</b>值向下可见、不可跨进程、查找是线性链;key 用私有类型,值保持小而不可变,深链本身就是性能问题。</p>
<h3 id="sec-11-6">11.6 使用规范:七条硬规则</h3>
<p><span class="tag">现象</span>代码编译通过、单测全绿,<code>go vet</code> 却在 CI 里报一行:<code>the cancel function returned by context.WithCancel should be called, not discarded, to avoid a context leak</code>。真正的问题不会当场炸,而是在压测半小时后以内存曲线的形式出现。</p>
<p><span class="tag">机制</span>这七条没有一条是编译器能强制执行的,全是接口边界上的约定。其中只有三条会引发运行时问题:不 cancel(泄露)、不响应 Done(泄露 goroutine)、传 nil(panic)。剩下四条的作用是让调用链保持可预测。</p>
<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 里成本最低的一道防线。它靠的是控制流分析:cancel 变量被创建后,所有返回路径上都没有被调用或传递出去,就报错。</p>
<p><span class="tag">代价</span>违反这些规则的代价不是编译错误,而是延迟暴露:ctx 存进结构体、超时没扣减、Done 没监听,都能一直跑到流量上来才现形;到那时你面对的是一份几千行的 goroutine dump,而不是一个红色测试。</p>
<p class="take"><b>一句话:</b>这七条是纪律不是语法——编译器只帮你查 lostcancel 一条,其余六条靠 review 和压测兜底。</p>
<h3 id="sec-11-7">11.7 goroutine 泄露的六种场景</h3>
<p><span class="tag">现象</span>压测 30 分钟,<code>runtime.NumGoroutine()</code> 从 1000 涨到 30000 且不回落;抓一份 goroutine dump,八成栈顶停在 <code>chan send</code> 或 <code>chan receive</code>。</p>
<p><span class="tag">机制</span>泄露的本质是<b>永久阻塞</b>:goroutine 卡在一个永远不会就绪的操作上,它的栈、变量、channel 引用就都不能回收。六种场景的共同点只有一个——阻塞点没有退出路径,而 ctx 恰好是最通用的那条退出路径。</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>runtime 定时器记录常驻(<b>1.22 及以前</b>无法被回收)</td><td><code>defer ticker.Stop()</code>;<b>1.23 起</b>不可达定时器已能被 GC 回收,但显式停仍是好习惯</td></tr>
</tbody>
</table>
</div>
<div class="box warn">
<span class="bt">易错点 · 建了 WithCancel 不 cancel 不会自己好</span>
<p>子 ctx 没被 cancel,就一直在父节点的 children 里挂着;父 ctx 活多久,这个已经死掉的子节点就跟着活多久。它持有的值、channel 也一并被钉住。<b>摘除只发生在 cancel 被调用的那一刻</b>,goroutine 退出、函数返回都不会替你摘。</p>
</div>
<p><span class="tag s">可跳过</span>这里要纠正一个常见说法:<code>time.NewTicker</code> 和 <code>time.NewTimer</code> <strong>不创建 goroutine</strong>。
<code>time/tick.go:36-44</code> 只做两件事:<code>make</code> 一个容量 1 的 channel,再调 <code>newTimer</code> 向 runtime 登记一条定时器记录;
到点后由 runtime 的定时器堆唤醒等待者,全程没有额外的 goroutine 被创建。所以忘 <code>Stop</code> 的后果是<strong>定时器记录和它的 channel 常驻</strong>,
不是「多了一个 goroutine」。<b>1.23 起</b>定时器实现重写,不可达的定时器即使没 <code>Stop</code> 也能被 GC 回收;
<b>1.22 及以前</b>则必须 <code>Stop</code>,否则这条记录会一直挂在定时器堆上,这才是老代码里「<code>defer ticker.Stop()</code>」的来源。</p>
<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>
<p>修法只有一句通用的:<b>凡是可能阻塞的地方,select 里都要有 Done 分支</b>。注意 fixed 里返回前要 cancel 父 ctx,否则生产者收不到信号,只是把泄露换了个位置。</p>
<p><span class="tag">代价</span>一个泄露的 goroutine 至少占 2KB 栈(按需增长,实际常到 8KB 以上),还牵着它能触达的整条对象图:channel 里的积压元素、闭包捕获的请求体、ctx 里的值。泄露单调递增——每次请求多几个,直到 OOM 或调度器被拖垮。</p>
<p class="take"><b>一句话:</b>goroutine 不会因为没人管它就退出,它只会卡在某个地方永远等;每个阻塞点配一个 Done 分支,是唯一通用解。</p>
<h3 id="sec-11-8">11.8 检测与防治</h3>
<p><span class="tag">现象</span>线上只做一件事:定时抓 <code>/debug/pprof/goroutine?debug=1</code>。第一行 <code>total 8342</code>,往下每个调用点后面跟着一个数字,8341 个卡在同一个 <code>chan send</code> 上——比读一遍代码快一百倍。</p>
<p><span class="tag">机制</span>两步走:先<b>计数</b>(同一种栈出现几次,就是几份泄露),再<b>看栈</b>(栈顶那个函数就是阻塞点)。debug=1 给聚合摘要,够定位;debug=2 给全量栈,用来确认完整调用链。</p>
<pre data-lang="go" data-name="暴露 pprof 的最小代价方式">import (
_ "net/http/pprof" // 只注册 handler,不起任何 goroutine
)
func main() {
// 单独开一个内网端口,不要挂在业务端口上
go func() {
_ = http.ListenAndServe("127.0.0.1:6060", nil)
}()
// ... 剩下的启动逻辑
}</pre>
<pre data-lang="bash" data-name="排查三步"># 1. 看数量与聚合栈:第一行 total,下面每个调用点一份计数
go tool pprof http://127.0.0.1:6060/debug/pprof/goroutine?debug=1
# 2. 看完整栈,定位阻塞点
curl 'http://127.0.0.1:6060/debug/pprof/goroutine?debug=2' | head -100
# 3. 对比两个时间点,只在后者里出现的调用就是新泄露
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、阻塞点有没有 Done 兜底。检测只能抓现行,设计才能让它压根不发生。</p>
<p><span class="tag">代价</span>pprof 的 goroutine 端点本身很便宜,但 <code>debug=2</code> 要把所有 goroutine 的栈全 dump 出来,秒级 STW,高峰期抓一次就是一次事故;goleak 只覆盖单测跑得到的路径,线上那部分永远得靠 dump 兜底。</p>
<p class="take"><b>一句话:</b>泄露只能被「数出来」不能被「猜出来」:定时抓一条计数曲线,比读十遍代码更快找到那个没退出的 goroutine。</p>
<h3 id="sec-11-9">11.9 超时串联实战</h3>
<p><span class="tag">现象</span>同一条链,repo 报了唯一键冲突,cache 那个分支却返回 <code>context.Canceled</code>——日志里两条错误同时出现,只有一条是真的。补日志的人以为缓存也挂了,转头去查连接池。</p>
<p><span class="tag">机制</span>把前面的点串成一条真实链路:入口 500ms 总预算,服务层并行查缓存和数据库。errgroup 派生的 ctx 在第一个非 nil 错误出现时被 cancel,另一个分支立刻收到 Canceled 退出。并行分支是<b>一损俱损</b>的,错误处理必须区分「自己错了」和「被别人取消了」。</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 (
cached *Order
cacheHit bool
)
g.Go(func() error {
o, err := s.cache.Get(ctx, id)
if err != nil {
return nil // 缓存未命中不算错误
}
cached, cacheHit = o, true
return nil
})
var repoOrder *Order
g.Go(func() error {
o, err := s.repo.Get(ctx, id)
if err != nil {
return fmt.Errorf("repo.Get: %w", err)
}
repoOrder = o
return nil
})
err := g.Wait() // Wait 返回时,两个闭包的写入都可见
if cacheHit {
return cached, nil // 缓存命中优先,repo 失败也不影响结果
}
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
return nil, status.Error(codes.DeadlineExceeded, "query timeout")
}
return nil, err
}
return repoOrder, nil
}</pre>
<p><code>errgroup.WithContext</code> 在第一个 goroutine 返回错误时取消派生 context,
另一个分支会收到 <code>context.Canceled</code> 并尽快退出,避免「一个失败、另一个还在跑」。</p>
<p>这里最容易写错的是共享变量:两个闭包各自只写自己的结果(缓存侧写 <code>cached</code>/<code>cacheHit</code>,仓储侧写 <code>repoOrder</code>),由 <code>g.Wait()</code> 建立 happens-before。如果两个闭包都去写同一个 <code>order</code>,<code>errgroup</code> 只在 <code>Wait</code> 处同步、闭包之间没有任何同步,<code>go test -race</code> 会直接报 write-write race。注意 <code>cancel</code> 仍然要 <code>defer</code>,errgroup 的取消不会释放父 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>
<p><span class="tag">代价</span>并行不是白来的:峰值 QPS 和连接数都会翻倍,而缓存命中优先的写法会吞掉 repo 的真实错误——上游只看到 200,脏数据在半小时后才被发现。所以并行分支要能独立回退,别让一条命门挂满全链。</p>
<p class="take"><b>一句话:</b>并行分支一损俱损,Canceled 是被取消不是被失败;错误要分层标注来源,否则排查时永远在怀疑第一个报错的那个。</p>
<h2 id="ch11-sum">全章回顾:症状 → 先查什么 → 回哪节</h2>
<div class="tablewrap">
<table>
<thead><tr><th>你看到的症状</th><th>先查什么</th><th>回哪节</th></tr></thead>
<tbody>
<tr><td>函数返回了,下游日志还在刷</td><td>ctx 有没有一路传下去,最内层阻塞点有没有监听 Done</td><td>11.3</td></tr>
<tr><td>504 一堆,下游 CPU 还是满的</td><td>超时是不是每层各设 500ms;数据源认不认 ctx</td><td>11.4</td></tr>
<tr><td>日志里 trace id 是空的</td><td>中间有没有 <code>Background()</code> 截断;key 是否私有类型</td><td>11.5</td></tr>
<tr><td>NumGoroutine 只涨不跌</td><td>pprof debug=1 里出现次数最多的那个栈</td><td>11.7</td></tr>
<tr><td>P99 从 80ms 跳到 2s</td><td>goroutine 数量趋势 + 栈顶是不是 <code>chan send</code></td><td>11.8</td></tr>
<tr><td>单测偶发 <code>-race</code> 报错</td><td>并行闭包有没有共享写同一个变量</td><td>11.9</td></tr>
</tbody>
</table>
</div>
<div class="box tip">
<span class="bt">面试怎么收尾</span>
<p>三句话:context 是一棵取消树,Done 关闭即广播,代价是调用 cancel 那一次同步递归;超时是绝对时刻,父子取更早,值过不了线而 deadline 能过线;泄露的本质是没有退出路径的阻塞,用 pprof 数出来、用 Done 分支消灭掉。最后补一句——它解决的从来不是「怎么杀死 goroutine」,而是「怎么让 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>