content(go): 每章开头新增「面试直答 · 30 秒版」口述答案块
This commit is contained in:
@@ -41,6 +41,16 @@
|
||||
|
||||
<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> 该不该用。
|
||||
|
||||
Reference in New Issue
Block a user