页边剪报

摘录:Go errgroup.WithContext 的 ctx 生命周期小坑

· 来源备忘:golang.org/x/sync/errgroup 文档与 GitHub Issue 讨论 #go#concurrency

看到一段线上 bug 复盘,根源是把 g, ctx := errgroup.WithContext(parentCtx) 返回的那个衍生 ctx 当成了后续逻辑的上下文继续往下传。

The derived Context is canceled the first time a function passed to Go returns a non-nil error or the first time Wait returns, whichever occurs first.
— pkg.go.dev/golang.org/x/sync/errgroup
// 错误示范:g.Wait() 返回后 groupCtx 已经被 cancel 了!
g, groupCtx := errgroup.WithContext(ctx)
g.Go(func() error { return fetchUser(groupCtx, uid) })
g.Go(func() error { return fetchQuota(groupCtx, uid) })
if err := g.Wait(); err != nil {
    return err
}
// 这里如果误传 groupCtx,必报 context canceled
return writeAuditLog(ctx, uid)

养成习惯:把衍生出来的变量显式命名成 gctx,不要用短变量声明覆盖外层的同名 ctx,一眼就能看出来作用域边界。