docs(go): 3-14 章按第 6 章标准统一改写
每章补:30 秒直答框、术语速查表、逐节「现象→机制→代价→一句话」、 2-3 张内联 SVG、2-4 处可跳过标记、全章回顾表,以及 3-5 处「易错点」警示框。 - 03 内存分配:补五级供货链、size class 取整、五层 pageAlloc 三张图 - 04 GC 标记:三色漏标画成四帧图,写屏障条件图,STW 时间线 - 05 GC 流程:补时间轴、清扫代数状态机、堆锯齿三张图,密度 7.3→0.6 - 07 map:旧实现结构图、扩容分流图、Swiss Table 控制字图 - 08 channel:环形缓冲图、发送三路径图、select 双顺序图 - 09 defer:defer 链表图、deferBits 位图、panic 展开链图 - 10 锁:Mutex 状态字位域图、RWMutex 计数器翻负图、WaitGroup 位域图 - 11 context:单链结构图、取消树图、超时时间轴 - 12 接口:接口值两字图、typed nil 对比图、调用路径图(并修好恒返回 nil 的示例) - 13 并发出题:令牌环图、乒乓时间线、errgroup 取消传播图 - 14 速查:执行链图、三条版本轨、Gin 请求时序图
This commit is contained in:
@@ -59,14 +59,28 @@
|
||||
以及线上 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>先看一个真实故障:网关设置了 500ms 超时,请求返回 504,但下游服务还在跑,
|
||||
CPU 被打满,日志里同一个 trace 十分钟后仍在打印。根因不是超时没生效,而是
|
||||
<strong>取消信号没有传下去</strong>:handler 返回了,它启动的 goroutine 和发起的 RPC 仍在按自己的节奏执行。</p>
|
||||
<p>并发程序里,「停止」比「启动」难。一个请求可能派生多个 goroutine、多层 RPC、数据库查询和缓存访问,
|
||||
调用方放弃等待时,需要有一种机制把「不用再做了」这个事实广播给整棵调用树。
|
||||
context 就是标准库给出的答案:它是一棵<strong>只读的树</strong>,父节点取消会级联取消所有子节点,
|
||||
同时还携带一个截止时间和少量请求级数据。</p>
|
||||
<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>
|
||||
@@ -78,20 +92,20 @@
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p>context 在 Go 1.7 进入标准库,之前是 <code>golang.org/x/net/context</code>。
|
||||
它的接口只有四个方法,刻意保持极小:</p>
|
||||
<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() <-chan struct{}
|
||||
Err() error
|
||||
Value(key any) any
|
||||
}</pre>
|
||||
<p>四个方法对应四种能力,合起来只有一条约定:<mark>Done 关闭后,Err 必须非 nil</mark>。
|
||||
所有实现都围绕这条约定展开。</p>
|
||||
<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>标准库没有用一个大而全的结构体,而是用四个小类型组合成一棵树。每个节点的 <code>Context</code> 字段
|
||||
指向父节点,形成单向链;取消从上往下传播,值查找从下往上回溯。</p>
|
||||
<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>
|
||||
@@ -103,10 +117,7 @@
|
||||
</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>
|
||||
<p>取消类的节点比根多带四样东西:</p>
|
||||
<pre data-lang="go" data-name="cancelCtx 的关键字段">type cancelCtx struct {
|
||||
Context
|
||||
|
||||
@@ -116,17 +127,59 @@
|
||||
err atomic.Value // 首次 cancel 时原子写入;Err() 无锁读
|
||||
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>
|
||||
<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><-chan struct{}</code>)限制调用方只能接收,不能发送或关闭。
|
||||
关闭动作必须由 context 内部完成,否则调用方一 <code>close</code>,父节点和兄弟节点都会收到假的取消信号。</p>
|
||||
<p>只读方向(<code><-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>创建子节点时,<code>propagateCancel</code> 会沿着父链向上找最近的可取消节点,把自己注册进它的 <code>children</code>。
|
||||
注册成功后,父节点取消时遍历 children 逐个调用 <code>cancel</code>,就完成了级联。</p>
|
||||
<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() // 无论如何都要调用,防止泄露
|
||||
|
||||
@@ -141,29 +194,62 @@ go func() {
|
||||
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 中删除。
|
||||
最后一步不是无条件的:它只在 <code>removeFromParent</code> 参数为 true 时才执行(<code>context.go:576-578</code>),
|
||||
而只有外部显式调用 <code>WithCancel</code> / <code>WithTimeout</code> 返回的 cancel 函数才传 true;
|
||||
父节点级联取消子节点时一律传 false(<code>child.cancel(false, err, cause)</code>),因为整棵子树都要丢弃,逐个摘除没有意义。
|
||||
摘除对「手动取消后父 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>
|
||||
<p>每次取消做四件事:关自己的 done、写 err、遍历 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">容易答错的点:Canceled 与 DeadlineExceeded 不相等</span>
|
||||
<p>超时取消的 <code>Err()</code> 是 <code>DeadlineExceeded</code>,不是 <code>Canceled</code>。
|
||||
如果要统一判断「是不是被取消」,用 <code>ctx.Err() != nil</code>,不要只比较 <code>Canceled</code>。</p>
|
||||
<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><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>
|
||||
<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() // 即使请求很快返回,也要释放定时器
|
||||
@@ -179,19 +265,63 @@ fmt.Println(context.Cause(ctx)) // order 42 cancelled by us
|
||||
defer resp.Body.Close()
|
||||
return io.ReadAll(resp.Body)
|
||||
}</pre>
|
||||
<p>超时预算要逐层扣减,而不是每层都设一个固定值。假设入口总预算 500ms,鉴权 50ms、查缓存 50ms、
|
||||
查数据库 200ms、调下游 150ms,那么每层应该基于父 context 的剩余时间再设上限,
|
||||
否则子层各自 500ms,父层早已超时,子层还在白干。</p>
|
||||
<p>还有一个能省掉一堆困惑的细节:如果父 ctx 的截止时间本来就比新设的更早,构造会直接退化成不带定时器的取消节点——预算自动继承,子层不可能比父层活得更久。</p>
|
||||
<pre data-lang="go" data-name="context.go:父的 deadline 更早时不再起定时器">func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) {
|
||||
if cur, ok := parent.Deadline(); ok && cur.Before(d) {
|
||||
return WithCancel(parent) // 已有更紧的预算,继承即可
|
||||
}
|
||||
// 否则才建 timerCtx 并起定时器
|
||||
}</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 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> 或直接在服务端按接口配置。
|
||||
「超时能不能传下去」是区分「会用 context」和「只传了 ctx 参数」的关键。</p>
|
||||
<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><code>WithValue</code> 只适合放<strong>请求级、不可变、小体积</strong>的元数据:trace id、用户身份、
|
||||
租户 id、灰度标记。不适合放数据库连接、logger、配置对象,更不适合当可选参数用。</p>
|
||||
<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 (
|
||||
@@ -207,17 +337,17 @@ 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>
|
||||
<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>
|
||||
@@ -227,13 +357,13 @@ func traceID(ctx context.Context) string {
|
||||
<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>
|
||||
<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>goroutine 泄露的本质是:某个 goroutine 永久阻塞在一个永远不会就绪的操作上,
|
||||
它持有的栈、变量、channel 引用都无法回收。压测时表现为 <code>runtime.NumGoroutine()</code> 只涨不跌,
|
||||
最终 OOM 或调度器过载。</p>
|
||||
<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>
|
||||
@@ -247,7 +377,11 @@ func traceID(ctx context.Context) string {
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p>这里要纠正一个常见说法:<code>time.NewTicker</code> 和 <code>time.NewTimer</code> <strong>不创建 goroutine</strong>。
|
||||
<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 回收;
|
||||
@@ -282,20 +416,31 @@ func fixed(ctx context.Context) {
|
||||
}
|
||||
}
|
||||
}</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>线上排查分三步:先看数量趋势,再看栈,最后定位到具体函数。</p>
|
||||
<pre data-lang="bash" data-name="goroutine 排查命令"># 1. 暴露 pprof(生产环境建议只在内网端口开)
|
||||
import _ "net/http/pprof"
|
||||
go func() { http.ListenAndServe("127.0.0.1:6060", nil) }()
|
||||
<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
|
||||
)
|
||||
|
||||
# 2. 看数量与栈摘要
|
||||
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
|
||||
|
||||
# 3. 看完整栈,定位阻塞点
|
||||
# 2. 看完整栈,定位阻塞点
|
||||
curl 'http://127.0.0.1:6060/debug/pprof/goroutine?debug=2' | head -100
|
||||
|
||||
# 4. 对比两个时间点的栈,找出持续存在的调用
|
||||
# 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) {
|
||||
@@ -308,12 +453,13 @@ func TestWorker(t *testing.T) {
|
||||
defer cancel()
|
||||
startWorker(ctx)
|
||||
}</pre>
|
||||
<p>防治的核心不是「检测」,而是<strong>给每个 goroutine 设计退出路径</strong>:
|
||||
启动时就想清楚谁会关 channel、谁会 cancel context、阻塞点有没有 <code>select</code> 兜底。</p>
|
||||
<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>把前面的点串成一个真实链路:HTTP 入口 500ms 总预算,服务层并行查缓存和数据库,
|
||||
任一失败就取消另一个,最后统一映射错误。</p>
|
||||
<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()
|
||||
@@ -357,12 +503,8 @@ func TestWorker(t *testing.T) {
|
||||
return repoOrder, nil
|
||||
}</pre>
|
||||
<p><code>errgroup.WithContext</code> 在第一个 goroutine 返回错误时取消派生 context,
|
||||
另一个请求会收到 <code>context.Canceled</code> 并尽快退出,避免「一个失败、另一个还在跑」。
|
||||
这里最容易写错的是共享变量:两个闭包各自只写自己的结果(缓存侧写 <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>,<code>errgroup</code> 的取消不会释放父 context 的定时器。</p>
|
||||
另一个请求会收到 <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 卡在
|
||||
@@ -370,11 +512,26 @@ func TestWorker(t *testing.T) {
|
||||
修法是把「满了就丢」写进 <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 关闭即广播;超时用 timerCtx,到期自动 cancel 并置
|
||||
DeadlineExceeded;WithValue 只放请求级元数据。使用上记住三条:第一个参数、defer cancel、下游要响应。
|
||||
泄露的本质是 goroutine 卡在无退出路径的阻塞上,排查用 pprof goroutine,防治靠启动时就设计好退出信号。」</p>
|
||||
<span class="bt">面试怎么收尾</span>
|
||||
<p>三句话:context 是一棵取消树,Done 关闭即广播,代价是调用 cancel 那一次同步递归;超时是绝对时刻,父子取更早,值过不了线而 deadline 能过线;泄露的本质是没有退出路径的阻塞,用 pprof 数出来、用 Done 分支消灭掉。最后补一句——它解决的从来不是「怎么杀死 goroutine」,而是「怎么让 goroutine 自己想走」。</p>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user