agones 项目中的 modern-go/concurrent:Go 并发 Map 兼容层与可取消 Goroutine 执行器实战解析

原创2026-10-09 23:46:422,329 阅读
文章标签:游戏开发后端云原生容器编排

agones 项目中的 modern-go/concurrent:Go 并发 Map 兼容层与可取消 Goroutine 执行器实战解析

modern-go/concurrent 是一个面向 Go 标准库能力补齐的并发工具包,它以 vendor 依赖的形式存在于 agones 仓库的 vendor/github.com/modern-go/concurrent 目录中。它提供两件核心武器:用于兼容 Go 1.9 以下版本的并发安全 concurrent.Map,以及带"所有权 + 可取消"语义的 goroutine 执行器 concurrent.Executor。读完本文,你将掌握这两个组件的完整 API、底层实现机制,以及它们在真实 Go 工程(如 agones 及其依赖链中的 json-iterator)中的典型用法。

一、包定位:它解决什么问题

Go 语言在 1.9 版本才正式引入 sync.Map(并发安全的 map)。在这之前,开发者要么自己用 sync.RWMutex 包裹普通 map,要么承受数据竞争的风险。concurrent.Map 正是为此而生的"移植层":它让同一份代码可以在 Go 1.9 以下和 1.9 以上的版本中无差别编译运行,从而让库作者写出可移植的并发代码。

与此同时,原生 go 关键字启动的 goroutine 缺乏统一的生命周期管理:无法批量取消、goroutine 内部 panic 会直接拖垮整个进程。concurrent.Executor 抽象则把 goroutine "挂靠"到某个执行器实例上,从而获得两个关键能力:

  • 通过停止执行器(Stop / StopAndWait / StopAndWaitForever)批量取消所有由其启动的 goroutine;
  • 通过回调统一捕获并记录 goroutine panic,默认行为不再导致应用程序崩溃。

从源码看,包内文件职责非常清晰(executor.go、unbounded_executor.go、go_above_19.go、go_below_19.go、log.go)。

二、concurrent.Map:跨版本并发安全 Map

2.1 设计思路:构建标签实现"双实现"

concurrent.Map 的核心设计是按 Go 版本选择不同实现,而不是自己重写一份:

  • Go 1.9 及以上(go_above_19.go):

    //+build go1.9
    
    package concurrent
    
    import "sync"
    
    // Map is a wrapper for sync.Map introduced in go1.9
    type Map struct {
        sync.Map
    }
    
    // NewMap creates a thread safe Map
    func NewMap() *Map {
        return &Map{}
    }
    

    它只是 sync.Map 的一个薄封装,API 与内嵌的 sync.Map 完全一致,性能与官方实现相同。

  • Go 1.9 以下(go_below_19.go):

    //+build !go1.9
    
    package concurrent
    
    import "sync"
    
    // Map implements a thread safe map for go version below 1.9 using mutex
    type Map struct {
        lock sync.RWMutex
        data map[interface{}]interface{}
    }
    
    // NewMap creates a thread safe map
    func NewMap() *Map {
        return &Map{
            data: make(map[interface{}]interface{}, 32),
        }
    }
    

    它内部持有一把 sync.RWMutex 和一个初始容量为 32 的普通 map,实现读多写少场景下的安全并发访问。

两个文件通过 //+build go1.9 与 //+build !go1.9 构建标签互斥,同一包名 concurrent、同一类型 Map,对外 API 完全一致——这正是"一份代码多版本可移植"的关键。

2.2 低版本实现:读锁与写锁分工

在 go_below_19.go 中可以看到两个核心方法的底层实现:

// Load is same as sync.Map Load
func (m *Map) Load(key interface{}) (elem interface{}, found bool) {
    m.lock.RLock()
    elem, found = m.data[key]
    m.lock.RUnlock()
    return
}

// Load is same as sync.Map Store
func (m *Map) Store(key interface{}, elem interface{}) {
    m.lock.Lock()
    m.data[key] = elem
    m.lock.Unlock()
}
  • Load 获取读锁(RLock),允许多个 goroutine 并发读;
  • Store 获取写锁(Lock),保证同一时刻只有一个写入者。

这是教科书式的 RWMutex 用法,读写互斥、读读共享,适合高频读取、低频写入的缓存类场景。

2.3 使用示例(README 原始代码)

README 给出的最简用法如下(完整代码见 README.md):

m := concurrent.NewMap()
m.Store("hello", "world")
elem, found := m.Load("hello")
// elem will be "world"
// found will be true
  • Store(key, value):写入键值对,两个参数均为 interface{};
  • Load(key):返回 (elem, found) 二元组,found 表示键是否存在,与 sync.Map 的语义一致。

需要说明的是:README 与源码当前只公开了 NewMap、Load、Store 三个 API(go_below_19.go 中的注释也仅声称这两者与 sync.Map 对应方法一致)。在 Go 1.9 以上的封装版本中,内嵌的 sync.Map 会把 Delete、Range、LoadOrStore 等方法一并"提升"到 Map 类型上;但在低版本实现中这些方法并未显式定义,因此若你的目标 Go 版本低于 1.9,请仅使用上述三个方法,以保证跨版本行为一致。

三、concurrent.Executor:带所有权与取消能力的 goroutine 管理

3.1 接口定义

executor.go 定义了执行器的核心抽象:

// Executor replace go keyword to start a new goroutine
// the goroutine should cancel itself if the context passed in has been cancelled
// the goroutine started by the executor, is owned by the executor
// we can cancel all executors owned by the executor just by stop the executor itself
// however Executor interface does not Stop method, the one starting and owning executor
// should use the concrete type of executor, instead of this interface.
type Executor interface {
    // Go starts a new goroutine controlled by the context
    Go(handler func(ctx context.Context))
}

接口只有唯一方法 Go(handler func(ctx context.Context))。三个要点值得强调:

  1. 替换 go 关键字:用它启动 goroutine,而不是裸 go;
  2. 基于 context 协作式取消:goroutine 内必须监听传入的 ctx.Done() 并自行退出,执行器只负责"广播取消信号";
  3. 所有权归属:goroutine 由执行器启动,即归执行器所有,停止执行器即可取消其名下全部 goroutine。注意接口本身没有 Stop 方法——启动并拥有执行器的一方应该持有具体类型(如 *UnboundedExecutor)而不是接口,以便调用停止方法。

3.2 UnboundedExecutor:具体实现

仓库中的具体实现是 UnboundedExecutor(unbounded_executor.go),意为"不限制存活 goroutine 数量的执行器":

type UnboundedExecutor struct {
    ctx                   context.Context
    cancel                context.CancelFunc
    activeGoroutinesMutex *sync.Mutex
    activeGoroutines      map[string]int
    HandlePanic           func(recovered interface{}, funcName string)
}
  • ctx / cancel:通过 context.WithCancel(context.TODO()) 创建(见 NewUnboundedExecutor),停止执行器本质就是调用 cancel();
  • activeGoroutines + activeGoroutinesMutex:以"启动点文件:行号"为键、计数为值,跟踪每个启动点当前存活的 goroutine 数量;
  • HandlePanic:可覆盖的 panic 回调字段,为 nil 时使用包级全局 HandlePanic。

创建方式(注意:不能用 &UnboundedExecutor{} 直接构造,必须走 NewUnboundedExecutor,因为它需要初始化 context 与内部 map):

executor := concurrent.NewUnboundedExecutor()

3.3 完整工作流(README 原始示例)

README 给出了一个完整到可直接运行的生命周期示例:

executor := concurrent.NewUnboundedExecutor()
executor.Go(func(ctx context.Context) {
    everyMillisecond := time.NewTicker(time.Millisecond)
    for {
        select {
        case <-ctx.Done():
            fmt.Println("goroutine exited")
            return
        case <-everyMillisecond.C:
            // do something
        }
    }
})
time.Sleep(time.Second)
executor.StopAndWaitForever()
fmt.Println("executor stopped")

流程解读:

  1. executor.Go(...) 启动一个 goroutine,内部用 select 同时监听 ctx.Done() 与 1ms 定时器;
  2. 主 goroutine 睡 1 秒,期间子 goroutine 每秒触发 1000 次 tick 执行业务逻辑;
  3. executor.StopAndWaitForever() 触发取消并永久阻塞等待,直到所有子 goroutine 退出;
  4. 子 goroutine 收到 ctx.Done() 后打印 "goroutine exited" 并 return,随后主 goroutine 打印 "executor stopped"。

这个模式本质上就是标准库 errgroup / context 协作取消范式的轻量封装:执行器把"取消"从手工管理 context 传播,收敛为"停止执行器"一个动作。

3.4 三种停止方式与内部等待机制

从 unbounded_executor.go 可以看到三种停止语义:

// Stop cancel all goroutines started by this executor without wait
func (executor *UnboundedExecutor) Stop() {
    executor.cancel()
}

// StopAndWaitForever cancel all goroutines started by this executor and
// wait until all goroutines exited
func (executor *UnboundedExecutor) StopAndWaitForever() {
    executor.StopAndWait(context.Background())
}

// StopAndWait cancel all goroutines started by this executor and wait.
// Wait can be cancelled by the context passed in.
func (executor *UnboundedExecutor) StopAndWait(ctx context.Context) {
    executor.cancel()
    for {
        oneHundredMilliseconds := time.NewTimer(time.Millisecond * 100)
        select {
        case <-oneHundredMilliseconds.C:
            if executor.checkNoActiveGoroutines() {
                return
            }
        case <-ctx.Done():
            return
        }
    }
}
  • Stop():只广播取消信号,不等待,立即返回;
  • StopAndWait(ctx):广播取消后,以 100ms 为周期轮询 checkNoActiveGoroutines(),直到所有 goroutine 退出;同时监听传入的 ctx.Done(),若外部想放弃等待可提前返回(等待本身也可取消);
  • StopAndWaitForever():等价于 StopAndWait(context.Background()),即无限期等待,直到所有 goroutine 干净退出。

checkNoActiveGoroutines(unbounded_executor.go)遍历 activeGoroutines 计数表,只要存在计数大于 0 的启动点就返回 false,并打印形如 UnboundedExecutor is still waiting goroutines to quit startFrom=xxx count=N 的 Info 日志。

3.5 全局执行器:GlobalUnboundedExecutor

包内还预置了一个全局单例(unbounded_executor.go):

// GlobalUnboundedExecutor has the life cycle of the program itself
// any goroutine want to be shutdown before main exit can be started from this executor
// GlobalUnboundedExecutor expects the main function to call stop
// it does not magically knows the main function exits
var GlobalUnboundedExecutor = NewUnboundedExecutor()

它的生命周期与整个程序一致:任何希望在 main 退出前被统一收尾的后台 goroutine,都可以挂到这个执行器上。源码注释明确提醒:GlobalUnboundedExecutor 期望 main 函数主动调用 Stop,它并不会神奇地感知 main 退出。因此在程序退出路径上记得调用 concurrent.GlobalUnboundedExecutor.StopAndWaitForever()。

3.6 内部启动与 panic 兜底

Go 方法的实现(unbounded_executor.go)做了三件"隐形"的事:

func (executor *UnboundedExecutor) Go(handler func(ctx context.Context)) {
    pc := reflect.ValueOf(handler).Pointer()
    f := runtime.FuncForPC(pc)
    funcName := f.Name()
    file, line := f.FileLine(pc)
    executor.activeGoroutinesMutex.Lock()
    defer executor.activeGoroutinesMutex.Unlock()
    startFrom := fmt.Sprintf("%s:%d", file, line)
    executor.activeGoroutines[startFrom] += 1
    go func() {
        defer func() {
            recovered := recover()
            // if you want to quit a goroutine without trigger HandlePanic
            // use runtime.Goexit() to quit
            if recovered != nil {
                if executor.HandlePanic == nil {
                    HandlePanic(recovered, funcName)
                } else {
                    executor.HandlePanic(recovered, funcName)
                }
            }
            executor.activeGoroutinesMutex.Lock()
            executor.activeGoroutines[startFrom] -= 1
            executor.activeGoroutinesMutex.Unlock()
        }()
        handler(executor.ctx)
    }()
}
  1. 启动点登记:通过 reflect + runtime.FuncForPC 拿到 handler 的函数名与"文件:行号",登记到计数表。这样 StopAndWait 能精确知道还有哪些位置启动的 goroutine 未退出;
  2. panic 捕获:goroutine 外层包了 defer recover()。panic 被 recover 后,优先调用实例字段 executor.HandlePanic,否则调用包级默认实现——进程不再因单个 goroutine panic 而崩溃;
  3. 退出计数:goroutine 结束后把对应启动点计数减一。

包级默认 panic 处理(unbounded_executor.go)会把 panic 值连同堆栈打印到日志:

var HandlePanic = func(recovered interface{}, funcName string) {
    ErrorLogger.Println(fmt.Sprintf("%s panic: %v", funcName, recovered))
    ErrorLogger.Println(string(debug.Stack()))
}

配套的日志出口在 log.go:

// ErrorLogger is used to print out error, can be set to writer other than stderr
var ErrorLogger = log.New(os.Stderr, "", 0)

// InfoLogger is used to print informational message, default to off
var InfoLogger = log.New(ioutil.Discard, "", 0)
  • ErrorLogger 默认输出到 os.Stderr,可被替换为其他 writer(如文件、自定义 log 实现);
  • InfoLogger 默认输出到 ioutil.Discard(即默认关闭),等待等待信息默认不可见,需要时可将它重定向到可见输出。

四、在 agones 仓库中的真实定位:vendor 依赖与 json-iterator 的运用

4.1 依赖来源与版本

本包不是 agones 业务代码直接调用的模块,而是作为第三方依赖被 vendored 进仓库。在 vendor/modules.txt 中可以查到其锁定版本:

# github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd

该版本由 agones 的 go.mod 间接引入(同目录的 go.sum 中也有对应记录),并被 Go Modules vendor 机制完整带入。

4.2 下游消费者:json-iterator 的解码/编码缓存

在本仓库 vendor 目录内,concurrent.Map 最直接的使用者是同为第三方依赖的 json-iterator/go。在 vendor/github.com/json-iterator/go/config.go 中可以清楚看到:

decoderCache *concurrent.Map
encoderCache *concurrent.Map
// ...
cfg.decoderCache = concurrent.NewMap()
cfg.encoderCache = concurrent.NewMap()
// ...
var cfgCache = concurrent.NewMap()

json-iterator 用 concurrent.NewMap() 构建了解码器缓存、编码器缓存以及全局配置缓存三张并发安全 map。这正是 concurrent.Map 的典型应用场景:缓存结构被多个 goroutine 并发读(查找已编译的 decoder/encoder),而写入(首次编译并缓存)相对低频——与低版本实现中 RWMutex 读多写少的设计目标完全吻合。这也间接说明:凡是"并发读为主、偶尔写入、希望跨 Go 版本可移植"的缓存 map,都可以直接套用 concurrent.Map 的模式。

4.3 仓库内的测试/验证手段

vendored 包自带的 test.sh 展示了其测试思路:

for d in $(go list ./... | grep -v vendor); do
    go test -coverprofile=profile.out -coverpkg=github.com/modern-go/concurrent $d
    ...
done

它用 -coverpkg 把覆盖率统计精确锚定到 github.com/modern-go/concurrent 包本身,遍历全部非 vendor 包运行测试并汇总覆盖率到 coverage.txt。如果你在自己的工程里引用了该库,可以用同样方式验证它被完整覆盖。

五、实践建议与注意事项

综合 README 与源码,使用本包时有几点值得留意:

  1. 明确你的 Go 版本再选择角色:如果目标运行环境包含 Go 1.9 以下版本,concurrent.Map 是你的跨版本并发 map 首选;若最低版本已 ≥ 1.9,直接用标准库 sync.Map 即可,concurrent.Map 此时只是薄封装。
  2. 用具体类型持有执行器:Executor 接口没有 Stop 方法,想要停止 goroutine,必须持有 *UnboundedExecutor 具体类型(或使用包级 GlobalUnboundedExecutor)。
  3. goroutine 内必须响应 context 取消:执行器的取消是协作式的——Stop 只调用 cancel(),业务 goroutine 必须监听 ctx.Done() 并自行 return,否则 StopAndWait/StopAndWaitForever 会一直等待。
  4. 程序退出前主动收尾全局执行器:GlobalUnboundedExecutor 不会自动感知 main 退出,需在退出路径显式调用其停止方法。
  5. 按需定制日志:默认 ErrorLogger 走 stderr、InfoLogger 静默;在正式服务中可把两者替换为结构化日志 writer,便于排查"goroutine 迟迟不退"与 panic 现场。
  6. 不要直接 &UnboundedExecutor{} 构造:内部 context、map、mutex 都依赖 NewUnboundedExecutor() 初始化,绕过工厂函数会得到不可用实例。

总的来说,modern-go/concurrent 是一个小而精的并发工具箱:concurrent.Map 解决历史 Go 版本的 API 缺口,concurrent.Executor 提供"启动—跟踪—取消—回收"完整的 goroutine 生命周期闭环。即使现代 Go 项目中可直接用 sync.Map 与标准库 context 替代大部分场景,理解它的接口设计(所有权归属、协作式取消、panic 兜底)对写出健壮的并发代码依然极具参考价值。

登录后查看全文
agones