Go race detector 没报错,channel 死锁却卡了三天

[复制链接]
发表于 前天 08:40 | 显示全部楼层 |阅读模式
问题现场

一个 Go 服务跑着跑着 QPS 掉到 0,进程没崩,pprof 的 goroutine 数量稳定在 2000 左右不动。第一反应是竞态,上了
  1. -race
复制代码
编译,跑了一周压测,一条 WARNING 都没有。

排查过程

先抓 goroutine profile:
  1. go tool pprof http://localhost:6060/debug/pprof/goroutine?debug=2
复制代码

输出里大量 goroutine 卡在同一行:
  1. goroutine 1842 [chan send, 9 minutes]:
  2. main.worker(0xc000123456)
  3.     /app/worker.go:47 +0x52
复制代码

全是
  1. chan send
复制代码
,9 分钟没动。但这不是数据竞态,是逻辑死锁——race detector 只检测内存访问冲突,goroutine 互相等 channel 它管不着。

回头翻
  1. worker.go:47
复制代码
:
  1. func worker(jobs <-chan Job) {
  2.     results := make(chan Result) // 无缓冲
  3.     go func() {
  4.         for r := range results {
  5.             save(r)
  6.         }
  7.     }()
  8.     for j := range jobs {
  9.         results <- process(j) // 47 行,卡这
  10.     }
  11.     close(results)
  12. }
复制代码

踩坑结论

下游
  1. save()
复制代码
慢的时候,无缓冲 results 把 worker 全堵死,jobs 队列积压,上游也堵。加个 buffer 只是缓解,真正的问题是没有取消路径,堵了就永远堵着。改成带 context 的写法:
  1. func worker(ctx context.Context, jobs <-chan Job) error {
  2.     results := make(chan Result, 16)
  3.     go func() {
  4.         defer close(results)
  5.         for r := range results {
  6.             save(r)
  7.         }
  8.     }()
  9.     for {
  10.         select {
  11.         case <-ctx.Done():
  12.             return ctx.Err()
  13.         case j, ok := <-jobs:
  14.             if !ok { return nil }
  15.             select {
  16.             case results <- process(j):
  17.             case <-ctx.Done():
  18.                 return ctx.Err()
  19.             }
  20.         }
  21.     }
  22. }
复制代码

教训:race detector 绿灯不代表没并发问题。看到 goroutine 卡在
  1. chan send
复制代码
/
  1. chan receive
复制代码
且时间戳很久,直接按死锁查,别在
  1. -race
复制代码
上浪费时间。
发表于 前天 08:40 | 显示全部楼层
问题类型:并发逻辑死锁(channel 阻塞),不是数据竞态,race detector 本来就管不到这类问题,别在这上面耗时间。

从 profile 看 2000 个 goroutine 全卡在 worker.go:47 的 chan send,说明接收端已经没人了。按下面几步查:

1. 把 debug=2 的完整栈按函数聚合成计数,看阻塞点是不是只有 send 和 recv 两类,确认是“发送方等接收方”还是反过来。
2. 重点看无缓冲 results 的接收方:谁负责 range results 或 <-results?如果接收方在某个错误分支提前 return,发送方就永久挂住。
3. 检查 worker 内层 goroutine 是否泄漏:外层函数返回后内层还在往 results 写,没人读。
4. 用 goleak 在测试里跑最小复现,或在 worker 入口加 select + ctx.Done() 兜底。

需要你贴出 worker.go:40-60 完整代码、results 的消费方代码,以及 goroutine profile 里除 send 外其他阻塞点的聚合结果。没有这些只能猜,我不猜。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

在本版发帖
关注公众号
QQ客服返回顶部