Goroutine Context 详细讲解
Go Context 详细讲解 context 是 Go 官方用来在 goroutine 之间传递取消信号、超时、截止时间和请求范围数据的标准库。它解决了并发编程中的核心问题:如何优雅地通知一组 goroutine 停止工作。 一、为什么需要 Context 1.1 没有 Context 的痛点 1 2 3 4 5 6 // 假设一个 HTTP 请求启动了 3 个 goroutine 处理子任务 func handler(w http.ResponseWriter, r *http.Request) { go fetchFromDB() // 用户断开连接,它还在跑 go callExternalAPI() // 超时了,它还在跑 go writeToCache() // 没人需要结果了,它还在跑 } 问题: 用户取消请求,goroutine 收不到通知,继续浪费资源 无法设置统一超时 无法在调用链中传递请求 ID、用户身份等数据 goroutine 泄漏 1.2 Context 的设计哲学 “一个请求,一棵 goroutine 树,一个 Context。” Context 是树形结构,根节点是 context.Background() 或 context.TODO() 父 Context 取消 → 所有子 Context 全部取消(级联) Context 是并发安全的,可被多个 goroutine 同时使用 Context 应该作为函数的第一个参数,命名为 ctx 二、Context 接口 1 2 3 4 5 6 7 8 9 10 11 12 13 type Context interface { // 返回 deadline 和是否设置了 deadline Deadline() (deadline time.Time, ok bool) // 返回一个 channel,在 Context 被取消时关闭 Done() <-chan struct{} // 返回取消原因(在 Done 关闭后才有意义) Err() error // 获取 key 对应的值 Value(key any) any } 关键点: ...