大家好,我是江湖十年。

Go 1.27 发布有一段时间了,我之前专门写过《Go 1.27 测试相关变化详解:新特性与升级避坑》,分享测试相关功能。今天再来分享一下 Go 1.27 新增的 goroutine leak profiler 能力,2026 年 9 月 Go 官方发表过《Goroutine Leak Profiles》,作者是 Vlad Saioc。文章介绍了 Go 1.27 新增的 goroutine leak profiler,它可以在运行中的 Go 程序里,包括生产环境,精准定位那些永久阻塞的 goroutine。本文是对这篇文章的中文翻译。

如下为译文:

原文地址:https://go.dev/blog/goroutine-leak-profiles

Vlad Saioc

2026 年 9 月 2 日

Go 的并发特性强大且易用,但正是这种易用,有时也会让经验丰富的开发者犯错。幸运的是,Go 生态提供了一些有用的调试工具,比如竞态检测器(race detector),但即便是现有工具,也可能漏掉一些并发 bug,比如本文要讨论的主题——goroutine 泄漏(goroutine leak)。

Goroutines 通过共享的并发原语(concurrency primitives)同步或交换信息,比如 channels、锁和 wait groups。在通信过程中,goroutines 经常会阻塞(block)在这些原语上,也就是等待某个条件满足;常见的例子包括等待获取已被持有的互斥锁,或从 channel 接收消息。Goroutines 也可能阻塞在操作系统操作上,比如从网络 socket 或文件读取数据。

如果一个 goroutine 被阻塞,而解除阻塞所需的条件永远不可能满足,我们就可以认为它泄漏了。随着时间推移,泄漏的 goroutines 越积越多,会因内存占用过高(泄漏的 goroutines 本身,或它们引用的内存)以及垃圾回收器带来的 CPU 开销而拖慢性能,尤其是在使用 GOMEMLIMIT 时。

Goroutine 泄漏出了名地难以检测。在单元测试中,最重要的突破之一是开源库 goleak,它可以在单个测试结束后,把所有未终止的 goroutines 标记为可疑对象。类似地,Go 1.25 在标准库中引入了 synctest 包,它让 Go 开发者能更好地控制并发事件的顺序,从而可靠地测试那些难以复现的场景,显著提升并发代码单元测试的质量。

遗憾的是,这两种方法都无法检查生产系统中的 goroutine 泄漏,尤其是在规模较大时,生产系统的行为可能超出测试覆盖的范围。Goroutine profiles 是基础手段,可以用来检查哪些操作阻塞了过多 goroutines,或分析增长趋势。但 goroutine profiles 无法区分哪些 goroutines 是泄漏的,哪些只是按设计暂时大量阻塞,比如微服务流量上涨导致的阻塞。同样,数量较少的泄漏可能潜伏多年而不被发现。

Go 1.27 引入了 goroutine leak profiler,这是一种灵活且轻量的机制,用于在运行中的 Go 程序里查找 goroutine 泄漏,包括生产系统。与以往需要人工分析的方法不同,这种机制很精确,几乎不会产生误报。代价是它只覆盖一部分 goroutine 泄漏:goroutines 永久阻塞在 channels 或 sync 包原语上。幸运的是,正如后面的例子所示,这已经覆盖了 goroutine 泄漏中相当大的一部分。

接下来几节会展示如何使用这个特性,然后给出一些可检测泄漏的补充示例,并介绍底层实现和取舍。

示例:并发 workers

考虑一个并发处理工作项的函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
type result struct {
res workResult
err error
}

func processWorkItems(ws []workItem) ([]workResult, error) {
// Process work items in parallel, aggregating results in ch.
ch := make(chan result)
for _, w := range ws {
go func() {
res, err := processWorkItem(w)
ch <- result{res, err}
}()
}

// Collect the results from ch, or return an error if one is found.
var results []workResult
for range len(ws) {
r := <-ch
if r.err != nil {
// This early return may cause goroutine leaks.
return nil, r.err
}
results = append(results, r.res)
}
return results, nil
}

因为 ch 是无缓冲 channel,每个 worker goroutine 在发送结果时都会阻塞,直到主 goroutine 从 channel 接收。如果 processWorkItems 因为错误而提前返回,接收循环就结束了,剩下的发送方 goroutines 会永远阻塞。

这个例子代表了一类在真实 Go 程序中常见的错误,包括 Uber 的生产服务也不例外。下面看看如何用新的 goroutine leak profiler 找到这些泄漏。

用 goroutine leak profiler 调试

这个 profile 可以通过 runtime/pprof 包使用,profile 类型名为 goroutineleak;也可以安装 net/http/pprof 包定义的 profile handlers 来使用。如果你的服务里已经配置了 net/http/pprof,那就什么都不用做!这个 profile 会自动出现在 /debug/pprof/goroutineleak 端点,无论 handlers 安装在哪个 host 和 port。

下面把前面的并发 bug 放到一个完整程序里,并配置好 net/http/pprof 包。这样你就可以自己动手试试了!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package main

import (
"errors"
"log"
"net/http"
_ "net/http/pprof"
"time"
)

type workItem int
type workResult int

func processWorkItem(w workItem) (workResult, error) {
time.Sleep(10 * time.Millisecond)
if w == 5 {
return 0, errors.New("simulated error")
}
return workResult(w * 2), nil
}

type result struct {
res workResult
err error
}

func processWorkItems(ws []workItem) ([]workResult, error) {
ch := make(chan result)
for _, w := range ws {
go func() {
res, err := processWorkItem(w)
ch <- result{res, err}
}()
}

var results []workResult
for range len(ws) {
r := <-ch
if r.err != nil {
return nil, r.err
}
results = append(results, r.res)
}
return results, nil
}

func main() {
// Start pprof server
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()

// Repeatedly trigger the leak
for {
items := []workItem{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
_, err := processWorkItems(items)
if err != nil {
log.Printf("Error processing items: %v", err)
}

time.Sleep(time.Second)
}
}

构建上面的程序,然后运行:

1
2
$ go build -o leaky
$ ./leaky

收集 profile

程序很快就会开始积累泄漏,然后你可以在 http://localhost:6060/debug/pprof 的 web UI 中查看。

或者用 curl 收集 goroutine leak profile,再用 go tool pprof 分析:

1
2
3
4
5
6
7
8
9
10
11
12
13
$ curl http://localhost:6060/debug/pprof/goroutineleak > leak.prof
$ go tool pprof leak.prof
Type: goroutineleak
Time: 2026-03-01 13:19:49 UTC
Entering interactive mode (type "help" for commands, "o" for options)
(pprof) list processWorkItems
Total: 116
ROUTINE ======================== main.processWorkItems.func1 in .../main.go
0 116 (flat, cum) 100% of Total
. . 31: go func() {
. . 32: res, err := processWorkItem(w)
. 116 33: ch <- result{res, err}
. . 34: }()

profile 显示泄漏发生在 ch <- result{res, err}(第 33 行),直接指出了罪魁祸首。值得注意的是,程序运行得越久,泄漏的 goroutines 数量就越多。

修复泄漏

只要给 ch 加上缓冲区就能修复:

1
ch := make(chan result, len(ws))

这样,即使 processWorkItems 提前返回,所有工作项 goroutines 也都能把消息发出去,而不会阻塞。

更多真实案例见这一节。

实现原理

这一节面向对 goroutine leak profiler 内部泄漏检测原理感兴趣的读者。如果只关心性能开销和限制,可以直接跳到这一节。

核心概念

先从一个初步观察开始:如果一个 goroutine 阻塞在某个并发原语上,而其他任何 goroutine 都无法访问这个原语(这里说的是无法通过内存中的引用访问),那它显然泄漏了。这已经是一条很强的线索,我们可以进一步推广,给出一个 goroutine 没有泄漏的定义,我们称之为存活性(liveness)。我们用归纳法形式化定义存活性:

一个 goroutine 是存活的(live),当且仅当:

  1. 它没有被并发原语阻塞,或者

  2. 至少有一个阻塞它的并发原语被另一个存活的 goroutine 引用。

基本情况很简单,没有被阻塞的 goroutines 显然没有泄漏。归纳步骤背后的假设是,任何没有泄漏的 goroutine,最终都可能用自己引用的并发原语,让其他被这些原语阻塞的 goroutines 恢复运行。

为了找出所有存活的 goroutines,我们从明显存活的、未被阻塞的 goroutines 出发,沿着它们持有的引用(也就是通过它们的局部变量)追踪,找出它们能访问的并发原语。然后逐步把阻塞在这些原语上的 goroutines 也标记为存活,重复这个过程,直到不再发现新的存活 goroutines。

幸运的是,Go runtime 已经通过垃圾回收器(GC)计算内存可达性,所以下一步就是改造 GC 来满足我们的需求。下面两张图可以快速对比两种 GC:

原始 GC 标记示意图
原始 GC 标记示意图

图片来自 Go 官方博客。

改造后的 GC 标记示意图
改造后的 GC 标记示意图

图片来自 Go 官方博客。

不需要彻底重写 GC。Go runtime 使用的是并发三色标记清除垃圾回收器(现在是 Green Tea 变体!),它的工作方式已经和我们的目标很契合。只需要做几处关键改动:

  1. 在初始阶段,常规 GC 会把所有 goroutines(以及全局变量)都标记为可达,这样它们永远不会被当作垃圾,也就是把它们当作根对象(mark root)。我们改成只把未被阻塞的 goroutines 作为根对象,因为它们一定是存活的。

  2. 接下来是标记阶段,GC 会从根对象出发,顺着引用关系一路追踪下去,把能访问到的对象都标记为可用内存。虽然我们不直接修改这个阶段,但第 1 步的改动会隐式保证 GC 只标记存活 goroutines 引用的内存。

  3. 标记阶段结束时,检查所有在第 1 步中没有被当作根对象的阻塞 goroutines。如果一个 goroutine 被至少一个在第 2 步中标记过的并发原语阻塞,就把它加入根集合,然后 GC 从第 2 步继续标记。这正好对应存活性定义中的归纳步骤。

  4. 所有存活的 goroutines 都找出来之后,任何没有被加入根集合的 goroutine,其状态都被设为泄漏。

  5. 最后,标记阶段会再跑一遍。这一次,所有被判定为泄漏的 goroutines 也会作为根对象加入根集合,让 GC 像常规运行那样完成标记,把它本来会标记的内存都标记出来。

GC 周期结束后,goroutine leak profiler 会像常规 goroutine profile 那样收集数据,并只筛选出严格意义上的泄漏 goroutines。

限制

上面的例子展示了 goroutine leak profiles 的用途。不过,垃圾回收器有一些限制,可能导致它漏掉一些泄漏:

  1. 内存可达范围过大(Memory overreach):如果一个并发原语一直可以通过全局变量或可运行的 goroutines 访问到,那么阻塞在它上面的 goroutines 永远不会被报告为泄漏,即使这个并发原语以后根本不会再被使用。

    可以通过更严格地管理对并发原语引用的访问,并更清晰地划定它们的生命周期来缓解。

  2. 非标准阻塞(Non-standard blocking):为了保证正确性,goroutine 泄漏检测严格限定在 Go 语言内置的并发原语上,包括:channel 的发送和接收操作(包括对 nil channels 的操作)、阻塞的 select 语句(也就是没有 default 分支,甚至包括没有任何 case 的 select 语句),以及 sync 包中的成员,具体是 Mutex、RWMutex、WaitGroup 和 Cond。

    因为其他原因阻塞的 goroutines,比如文件 IO、网络 IO 或直接系统调用,永远不会被当作泄漏。这条规则同样适用于自定义的、用户实现的并发机制,比如自旋锁,除非它们的底层实现依赖上面列出的原语。

  3. 不确定性(Non-determinism):泄漏只有在发生之后才能被检测到,无法提前预测,所以在不稳定的程序里复现和诊断泄漏仍然是个挑战。为了获得最好的效果,建议混合使用多种方法:在包括生产在内的各个层面使用 goroutine leak profiles,同时配合用 goleak 和 synctest 插桩的完整测试套件。

性能影响

Goroutine 泄漏检测在设计上尽量降低性能影响,但仍然有一些成本。

内存开销可以忽略不计,只是一些用于记录状态的少量额外内存;不过 goroutine 泄漏检测可能比常规 GC 慢。最能说明问题的是一个我们称为“菊花链”(daisy-chain)的极端情况:

daisy-chain 示意图
daisy-chain 示意图

图片来自 Go 官方博客。

在这个没有泄漏的例子中,可运行的 goroutine G₀ 持有原语 P₁ 的引用,P₁ 阻塞了 G₁,依此类推。

这意味着,要证明某个 Pᵢ₊₁ 是存活的,必须先证明 Pᵢ 是存活的,这带来两项成本:

  1. GC 标记阶段实际上会被 goroutines 的扫描顺序串行化,因为从某个 Pᵢ 可达的所有内存都必须先标记完,Pᵢ₊₁ 才能被加入根集合。

  2. 目前每一轮标记结束时都会检查所有阻塞的 goroutines,一个 GC 周期最坏情况下是 O(n²) 步,其中 n 是所有 goroutines 的总数。

第二点最终可以优化,但第一点是泄漏检测的固有局限,无法绕过。

尽管如此,还是要提醒读者:除非通过 runtime flags 另行配置,GC 仍然会和用户代码并发运行。而且,如果一个 goroutine 泄漏在某个时间点能被观察到,那么在同一次执行的未来任何时间点也能被观察到。所以周期性采集 profile 的基础设施可以调整采集频率,比如每 4 小时一次,把开销降到最低,而几乎不损失泄漏检测能力。

致谢

Goroutine 泄漏检测是奥胡斯大学、圣路易斯华盛顿大学和 Uber 合作研究的成果,相关论文是 “Dynamic Partial Deadlock Detection and Recovery via Garbage Collection”(Saioc 等,ASPLOS 2025)。

从学术原型到真正的 Go 特性,离不开 Google Go 团队的 Michael Knyszek 和 Michael Pratt,以及 PJ Malloy(@thepudds)的指导。

补充示例

下面是一些会导致泄漏的编码模式,来自工业级代码库和开源项目,按复杂度从低到高排列。

你可以在 Go playground 上快速试用 goroutine 泄漏检测器,也可以拿自己的泄漏来实验。

示例:重复发送

最简单的泄漏之一,是向 channel 发送了比预期更多的消息。下面这个例子里,一个 goroutine 预期通过无缓冲 channel 向主 goroutine 发送一条消息。但在错误分支里,发送操作之后漏掉了 return 语句。因此,每次遇到错误时,发送方都会尝试发送两条消息,从而造成泄漏。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func DoubleSend() {
ch := make(chan any)
go func(err error) {
if err != nil {
// In case of an error, send nil.
ch <- nil
// Return statement is missing.
}
// Otherwise, continue with normal behaviour.
// This send is still executed, which causes a leak in the error case.
ch <- struct{}{}
}(fmt.Errorf("error"))
// Receive only one message.
<-ch
}

虽然 profile 不会明确指出是漏了 return 导致的,但至少会把泄漏的发送操作标出来,把你引到出问题的函数。

1
2
3
4
5
6
7
8
9
10
11
(pprof) list DoubleSend
Total: 1
ROUTINE ======================== main.DoubleSend.func1 in .../main.go
0 1 (flat, cum) 100% of Total
. . 118: go func(err error) {
. . 119: if err != nil {
. . 121: ch <- nil
. . 123: }
. 1 126: ch <- struct{}{}
. . 127: }(fmt.Errorf("error"))
. . 129: <-ch

这个泄漏很好修,只要在错误分支的发送操作后加上 return 就行。

示例:提前返回

相反的情况同样常见:接收方在某些控制流路径上跳过了通信操作,这实际上就是开头示例的简化版。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Incoming error simulates an error produced internally.
func EarlyReturn(err error) {
ch := make(chan any)

// Create a worker goroutine.
go func() {
// Send something to the channel.
// Leaks if the parent goroutine terminates early.
ch <- struct{}{}
}()

if err != nil {
// The parent goroutine quits too early in case of an error.
// Sender leaks.
return
}

// Receive is only executed if there is no error.
<-ch
}

profile 会把泄漏暴露出来:

1
2
3
4
5
6
7
ROUTINE ======================== main.EarlyReturn.func1 in .../main.go
0 1 (flat, cum) 100% of Total
. . 140: go func() {
. 1 143: ch <- struct{}{}
. . 144: }()
. . 145:
. . 146: if err != nil {

这个泄漏可以通过给 ch 一个大小为 1 的缓冲区来解决。

示例:超时

上面提前返回模式的一种变体涉及 contexts 和非确定性选择(select 语句):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
func Timeout(ctx context.Context) {
// An unbuffered channel is used to coordinate
// a worker and parent thread
ch := make(chan any)

// Create worker goroutine
go func() {
// Perform some work then signal to the parent thread.
ch <- struct{}{}
}()

// Wait for message from worker or context
// to be cancelled or timed out.
select {
case <-ch: // Receive message from worker
case <-ctx.Done():
// Sender leaks because there is no
// future rendezvous over the channel.
}
}

如果 context 在发送方与父 goroutine 同步之前就被取消,发送方就会泄漏:

1
2
3
4
5
6
7
(pprof) list Timeout
Total: 10
ROUTINE ======================== main.Timeout.func1.1 in .../main.go
0 10 (flat, cum) 100% of Total
. . 198: go func() {
. 10 201: ch <- struct{}{}
. . 202: }()

和前一个例子一样,修复方法是给 channel 一个大小为 1 的缓冲区。

示例:range channel 却没有关闭

用 range 遍历 channels 可以让你在循环中反复从 channel 接收值。一旦 channel 关闭,并且 channel 缓冲区里已入队的值都被接收完,循环就会退出。

重要的是,如果 channel 永远不关闭,range 循环会永远阻塞执行它的 goroutine。省略 close 操作是一个常见错误,比如下面这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Incoming list of items and the number of workers.
func noCloseRange(list []any, workers int) {
// Create a channel that distributes work items.
ch := make(chan any)

// Create the worker goroutines.
for i := 0; i < workers; i++ {
go func() {
// Each worker pulls items from the channel
// and then processes it.
for item := range ch {
// Process each item
_ = item
}
}()
}

// Queue items to the workers by using the channel.
for _, item := range list {
// The parent leaks by sending an item if workers == 0
// or if all the workers panic, but the panic is recovered.
ch <- item
}
// Otherwise, the channel is never closed, so workers
// leak once there are no more items left to process.
}

...
go noCloseRange([]any{1, 2, 3}, 3) // Leaks all 3 workers

这样的程序,goroutine leak profile 会包含下面这些内容:

1
2
3
4
5
6
7
8
9
10
Type: goroutineleak
(pprof) list noCloseRange.func1
Total: 4
ROUTINE ======================== main.noCloseRange.func1 in .../main.go
0 3 (flat, cum) 75.00% of Total
. . 82: go func() {
. 3 84: for item := range ch {
. . 86: _ = item
. . 87: }
. . 88: }()

我们看到 3 个 workers 都阻塞在 range ch 上,这已经足够提示泄漏的原因了。修复方法很简单,所有消息发送完之后关闭 channel:

1
2
3
4
5
for _, item := range list {
ch <- item
}
// All items have been sent. It is now safe to close.
close(ch)

额外发现! 眼尖的读者可能发现这个例子还有另一个潜在泄漏:如果 workers 的数量被误设为 0,父 goroutine(发送方)就会泄漏:

1
go noCloseRange([]any{1, 2, 3}, 0) // Sender leaks with 0 workers

profile 同样能捕获:

1
2
3
4
5
6
7
8
9
(pprof) list noCloseRange$
Total: 4
ROUTINE ======================== main.noCloseRange in .../main.go
0 1 (flat, cum) 25.00% of Total
. . 76:func noCloseRange(list []any, workers int) {
...
. . 92: for _, item := range list {
. 1 95: ch <- item
. . 96: }

虽然在真实的生产系统中可以假设 workers > 0 一定成立,但 goroutine leak profiles 仍然可以用来隐式监控那些万一发生的违规情况,而不需要保守地加上 workers <= 0 检查。

示例:违反方法契约

到目前为止,这些模式涉及的代码范围都相对有限。但当功能分散到多个函数、方法和包中,实现又被接口遮挡时,手动检测泄漏的难度会急剧上升。

本节就是一个例子:自定义的 worker 类型内嵌了两个 channel 字段,ch 和 done,它的 Start 方法会创建一个循环 goroutine,用 select 语句同时读这两个 channels。这个 goroutine 只有通过 done channel 收到消息才能终止,而 done 由 Stop 方法关闭。

Start 方法可以被调用任意多次,但只要调用过至少一次,最终就应该调用 Stop。

因此,Start 和 Stop 构成了一种隐式契约,规定了方法的调用顺序。破坏这个契约会导致不良行为,在这个例子里就是 goroutine 泄漏:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
func MethodContractViolation() {
items := make([]any, 10)
// Create a new worker
w := NewWorker()

// Start worker
w.Start()

// Operate on worker
for _, item := range items {
w.AddToQueue(item)
}
// Exits without calling ’Stop’.
}

type worker struct {
ch chan any
done chan any
}

type Worker interface {
Start()
Stop()
AddToQueue(item any)
}

func NewWorker() Worker {
return &worker{
ch: make(chan any),
done: make(chan any),
}
}

// Start spawns a background goroutine that extracts items pushed to the queue.
func (w *worker) Start() {
go func() {
for {
select {
case <-w.ch: // Normal workflow
case <-w.done:
return // Shut down
}
}
}()
}

func (w *worker) Stop() {
// Allows goroutine created by Start to terminate
close(w.done)
}

func (w *worker) AddToQueue(item any) {
w.ch <- item
}

在实践中,这个问题会更麻烦,因为这类自定义类型通常只以接口形式导出,这个例子里就是没有透露实现细节的 Worker 类型。客户端甚至可能根本不知道底层实现,于是在不知不觉中违反了隐式契约。

幸运的是,抓取 goroutine leak profile 可以揭示这个缺陷:

1
2
3
4
5
6
7
8
9
10
(pprof) list Start
Total: 1
ROUTINE ======================== main.(*worker).Start.func1 in .../main.go
0 1 (flat, cum) 100% of Total
. . 266: go func() {
. . 267: for {
. 1 268: select {
. . 269: case <-w.ch:
. . 270: case <-w.done:
. . 271: return

修复方法自然是顺着线索找到 Start 的调用处,补上一次 Stop 调用。

示例(Cockroach):漏掉 Unlock

下面这个例子来自 CockroachDB。它在循环中获取并释放锁,但在执行 break 语句之前忘了解锁:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
type Gossip struct {
mu sync.Mutex
closed bool
}

func (g *Gossip) bootstrap() {
for {
g.mu.Lock()
if g.closed {
// Missing g.mu.Unlock
break
}
g.mu.Unlock()
}
}

func Cockroach584() {
g := &Gossip{
closed: true,
}
// ...
g.bootstrap()
g.bootstrap() // Causes a leak
}

这种情况下,goroutine 在获取锁失败时会泄漏。

1
2
3
4
5
6
7
8
9
10
11
(pprof) list Gossip
Total: 1
ROUTINE ======================== main.(*Gossip).bootstrap in .../main.go
0 1 (flat, cum) 100% of Total
. . 165:func (g *Gossip) bootstrap() {
. . 166: for {
. 1 167: g.mu.Lock()
. . 168: if g.closed {
. . 170: break
. . 171: }
. . 172: g.mu.Unlock()

在 break 之前加一次 Unlock 调用即可修复。

示例(etcd):意料之外的 channel 操作顺序

这个例子来自 etcd,展示了 channel 操作之间意料之外的顺序如何导致 goroutine 泄漏:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
type node struct {
status chan chan struct{}
stop chan struct{}
done chan struct{}
}

func (n *node) Status() struct{} {
c := make(chan struct{})
n.status <- c
return <-c
}

func (n *node) run() {
for {
select {
case c := <-n.status:
c <- struct{}{}
case <-n.stop:
close(n.done)
return
}
}
}

func (n *node) Stop() {
select {
case n.stop <- struct{}{}:
case <-n.done:
return
}
<-n.done
}

func Etcd6857() {
n := &node{
status: make(chan chan struct{}),
stop: make(chan struct{}),
done: make(chan struct{}),
}
go n.run()
go n.Status()
go n.Stop()
}

run 方法启动一个循环,预期反复从 status channel 接收消息(由调用 Status 方法发送)。同时,它也可以从 stop channel 接收一条消息(由 Stop 方法发送),收到后关闭 done channel 并退出。Stop 方法本身随后会等待从 done 接收消息,一旦 done 关闭,它就会解除阻塞。

如果 run、Status 和 Stop 方法并发执行,就可能发生泄漏。Stop 和 run 这两个 goroutines 可能完成同步并退出,却没有接收 Status 发出的消息,导致 Status 永远阻塞。

1
2
3
4
5
6
7
8
9
(pprof) list Status
Total: 8
ROUTINE ======================== main.(*node).Status in .../main.go
0 8 (flat, cum) 100% of Total
. . 16:func (n *node) Status() struct{} {
. . 17: c := make(chan struct{})
. 8 18: n.status <- c
. . 19: return <-c
. . 20:}

把发往 status 的发送操作包进 select 语句,让另一个 case 分支尝试从 done 接收消息,这样,当 Status 在竞争中输给 Stop 调用时,运行 Status 的 goroutine 就能优雅退出。

示例(Kubernetes):channels 和 mutexes 相互阻塞

这个例子出现在 Kubernetes 中,是 channels 和锁混用导致的结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
type Connection struct {
closeChan chan bool
}

type idleAwareFramer struct {
resetChan chan bool
writeLock sync.Mutex
conn *Connection
}

func (i *idleAwareFramer) monitor() {
var resetChan = i.resetChan
for range i.conn.closeChan {
i.writeLock.Lock()
close(resetChan)
i.resetChan = nil
i.writeLock.Unlock()
break
}
}

func (i *idleAwareFramer) WriteFrame() {
i.writeLock.Lock()
defer i.writeLock.Unlock()
if i.resetChan == nil {
return
}
i.resetChan <- true
}

func NewIdleAwareFramer() *idleAwareFramer {
return &idleAwareFramer{
resetChan: make(chan bool),
conn: &Connection{
closeChan: make(chan bool),
},
}
}

func Kubernetes6632() {
i := NewIdleAwareFramer()

go func() {
i.conn.closeChan <- true
}()
go i.monitor()
go i.WriteFrame()
}

运行 WriteFrame 的 goroutine 可能先获取 idle-aware framer 的锁,然后向 resetChan channel 发送消息,而 monitor goroutine 此时正等待从 closeChan channel 接收消息。消息发出后,monitor goroutine 会尝试获取同一把锁。但由于 resetChan 上没有任何流量,发送操作会永远阻塞,导致 WriteFrame goroutine 无法释放锁。于是两个 goroutines 都泄漏了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
(pprof) list AwareFramer
Total: 200
ROUTINE ======================== main.(*idleAwareFramer).WriteFrame in .../main.go
0 100 (flat, cum) 50.00% of Total
. . 32:func (i *idleAwareFramer) WriteFrame() {
. . 33: i.writeLock.Lock()
. . 34: defer i.writeLock.Unlock()
. . 35: if i.resetChan == nil {
. . 36: return
. . 37: }
. 100 38: i.resetChan <- true
. . 39:}
ROUTINE ======================== main.(*idleAwareFramer).monitor in .../main.go
0 100 (flat, cum) 50.00% of Total
. . 21:func (i *idleAwareFramer) monitor() {
. . 22: var resetChan = i.resetChan
. . 23: for range i.conn.closeChan {
. 100 24: i.writeLock.Lock()
. . 25: close(resetChan)

修复方法是在 monitor goroutine 从 closeChan 收到消息后,另外启动一个 goroutine,在尝试获取锁之前先把 resetChan 排空。

示例(Moby):误用 sync.WaitGroup

下面这个 Moby 中的例子展示了 wait groups 如何导致泄漏:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
type Manager struct {
plugins []int
}

func (pm *Manager) init() {
var group sync.WaitGroup
group.Add(len(pm.plugins))
for _, p := range pm.plugins {
go func(p int) {
defer group.Done()
}(p)
group.Wait() // Block here
}
}

func Moby25384() {
pm := &Manager{
plugins: []int{1, 2},
}
go pm.init()
}

group 这个 wait group 会根据插件管理器 pm 持有的插件数量增加计数器,然后遍历每个插件并启动一个 goroutine。每个 goroutine 完成任务后调用 Done 减少计数器。然而,group 错误地在循环体内部调用了 Wait,而不是在循环之后!当管理器持有多个插件时,运行 init 方法的 goroutine 就会泄漏。

1
2
3
4
5
6
7
8
9
10
11
(pprof) list init
Total: 1
ROUTINE ======================== main.(*Manager).init in .../main.go
0 1 (flat, cum) 100% of Total
. . 17: group.Add(len(pm.plugins))
. . 18: for _, p := range pm.plugins {
. . 19: go func(p int) {
. . 20: defer group.Done()
. . 21: }(p)
. 1 22: group.Wait() // Block here
. . 23: }

把 Wait 移到循环外面即可轻松修复。

示例(Moby):channels 和 mutexes 相互阻塞

Moby 中的另一个例子展示了 channels 和锁混用导致的泄漏:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
type (
State struct {
Health *Health
}
Container struct {
sync.Mutex
State *State
}

Store struct {
ctr *Container
}

Daemon struct {
containers Store
}

Health struct {
stop chan struct{}
}
)

func (d *Daemon) StateChanged() {
c := d.containers.ctr
c.Lock()
d.updateHealthMonitorElseBranch(c)
defer c.Unlock()
}

func (d *Daemon) updateHealthMonitorElseBranch(c *Container) {
c.State.Health.CloseMonitorChannel()
}

func (s *Health) CloseMonitorChannel() {
if s.stop != nil {
s.stop <- struct{}{}
}
}

func monitor(c *Container, stop chan struct{}) {
for {
select {
case <-stop:
return
default:
handleProbeResult(c)
}
}
}

func handleProbeResult(c *Container) {
c.Lock()
defer c.Unlock()
// Additional work...
}

func NewDaemonAndContainer() (*Daemon, *Container) {
c := &Container{
State: &State{&Health{
stop: make(chan struct{}),
}},
}
d := &Daemon{Store{c}}
return d, c
}

func Moby28462() {
d, c := NewDaemonAndContainer()
go monitor(c, c.State.Health.stop)
go d.StateChanged()
}

调用 StateChanged 的 goroutine 可能先获取 daemon 中保存的 container 的锁,然后在 daemon 上调用 updateHealthMonitorElseBranch 方法,尝试向 container 的 stop channel 发送消息。然而,如果消息还没有被接收,运行 monitor 的 goroutine 可能收不到 stop 上的消息,而是选择 select 语句的 default 分支继续执行。这样它就会尝试获取同一把 container 锁,而这把锁已经被 StateChanged goroutine 持有,最终两个 goroutines 都泄漏。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
(pprof) list .CloseMonitorChannel
Total: 2
ROUTINE ======================== main.(*Health).CloseMonitorChannel in .../main.go
0 1 (flat, cum) 50.00% of Total
. . 66:func (s *Health) CloseMonitorChannel() {
. . 67: if s.stop != nil {
. 1 68: s.stop <- struct{}{}
. . 69: }
. . 70:}
(pprof) list main.handleProbeResult
Total: 2
ROUTINE ======================== main.handleProbeResult in .../main.go
0 1 (flat, cum) 50.00% of Total
. . 83:func handleProbeResult(c *Container) {
. 1 84: c.Lock()
. . 85: // Additional work...
. . 86: defer c.Unlock()
. . 87:}

修复方法是关闭 stop channel,而不是向它发送消息。因为关闭 channel 不是阻塞操作,StateChanged goroutine 就能释放锁。反过来,这又会解除 monitor goroutine 的阻塞,让它在下一轮循环中选择已经不再阻塞的 <-stop 分支并退出。

原文完。

希望此文能对你有所启发。

延伸阅读

联系我