← 中文资源

简体中文版本

首个错误触发兄弟任务取消

实现带上下文取消的最简 errgroup:第一个错误取消共享上下文,Wait 等待全部任务结束后返回该错误。

阅读英文原文

题目

实现 Group 类型,提供 WithContext(parent)、Go(fn) 和 Wait()。每个任务函数接收组内共享的 context。第一个返回非 nil 错误的任务必须取消该 context,使遵守取消信号的兄弟任务尽快退出。Wait 要等待所有已启动的 goroutine 结束,然后返回第一个错误;全部成功时返回 nil,后续错误不能覆盖第一个错误。

  • 输入:父 context 和若干接收 context 的任务函数。
  • 输出:第一个非 nil 错误;全部成功时为 nil。Wait 返回前所有任务都已结束。

解题思路

WithContext 从父 context 派生一个可取消的子 context。Go 先给 WaitGroup 加一,再启动 goroutine;任务返回非 nil 错误时,用 sync.Once 保存错误并调用 cancel。多个任务同时失败时,Once 保证只有一个赢家,避免竞争覆盖。Wait 通过 WaitGroup 的 happens-before 关系安全地读取该错误。

Wait 先阻塞在 wg.Wait(),之后无论成功还是失败都调用 cancel,释放子 context 及其定时器资源。由于 g.err 的写入发生在 wg.Done 之前,而 Wait 在 wg.Wait 之后读取,因此不存在数据竞争。任务必须配合 context 取消,否则即使 context 已取消,Wait 仍会被阻塞,这是该模型的边界。

参考实现要点

  1. Group 保存 ctx、cancel、sync.WaitGroup、sync.Once 和 err。
  2. WithContext 使用 context.WithCancel(parent) 创建子 context。
  3. Go 中 defer wg.Done(),任务失败时执行 once.Do 保存错误并取消。
  4. Wait 先等待所有 goroutine,再调用 cancel 清理资源,最后返回 g.err。
  5. 首次错误之后的其他错误被 Once 忽略,不覆盖根因。

常见错误

  • 在 Wait 中返回 ctx.Err(),把 context.Canceled 当成根因,掩盖真实任务错误。
  • 不用 Once 直接写 g.err,多个 goroutine 并发写入产生数据竞争。
  • Wait 在 wg.Wait 之前读取 err,可能读到零值或发生竞争。
  • 任务不监听 ctx.Done,取消信号无法缩短等待时间。

验证方式

运行失败样例应输出 boom,成功样例应输出 。再加入一个等待 ctx.Done 的任务,确认它在首个错误后提前退出;加入第二个错误,确认返回值仍是第一个。用 -race 重复运行检查竞争,并测试零任务、大量任务同时失败、以及父 context 预先取消的情况。最后观察不监听取消的任务会拖慢 Wait,理解协作式取消的约束。

代码示例

package main

import (
    "context"
    "errors"
    "fmt"
    "sync"
)

type Group struct {
    ctx    context.Context
    cancel context.CancelFunc
    wg     sync.WaitGroup
    once   sync.Once
    err    error
}

func WithContext(parent context.Context) *Group {
    ctx, cancel := context.WithCancel(parent)
    return &Group{ctx: ctx, cancel: cancel}
}

func (g *Group) Go(fn func(context.Context) error) {
    g.wg.Add(1)
    go func() {
        defer g.wg.Done()
        if err := fn(g.ctx); err != nil {
            g.once.Do(func() {
                g.err = err
                g.cancel()
            })
        }
    }()
}

func (g *Group) Wait() error {
    g.wg.Wait()
    g.cancel()
    return g.err
}

func main() {
    group := WithContext(context.Background())
    group.Go(func(context.Context) error {
        return errors.New("boom")
    })
    group.Go(func(ctx context.Context) error {
        <-ctx.Done()
        return ctx.Err()
    })
    fmt.Println(group.Wait())

    ok := WithContext(context.Background())
    ok.Go(func(context.Context) error { return nil })
    ok.Go(func(context.Context) error { return nil })
    fmt.Println(ok.Wait())
}