GoLang教程——Context上下文实战
大家好,我是极客老墨。 写并发程序时,经常遇到这样的场景:用户关闭了浏览器,但后台的数据库查询还在跑;API 调用超时了,但 Goroutine 还在等待响应。这些"失控"的 Goroutine 会浪费资源,甚至导致内存泄漏。 Go 的 Context 就是用来解决这个问题的。它能控制 Goroutine 的生命周期,实现超时、取消和数据传递。 这篇就聊聊 Context 的核心用法,看看它是怎么管理并发任务的。 Context 是什么 Context 是一个接口,定义了四个方法: 1type Context interface { 2 Deadline() (deadline time.Time, ok bool) 3 Done() <-chan struct{} 4 Err() error 5 Value(key interface{}) interface{} 6} 核心功能: 取消信号:通知 Goroutine 停止工作 超时控制:限制任务执行时间 数据传递:在调用链中传递元数据 创建 Context Go 提供了几个函数来创建 Context。 Background 和 TODO 1import "context" 2 3// Background:根 Context,通常在 main 函数中使用 4ctx := context.Background() 5 6// TODO:当不确定用什么 Context 时使用 7ctx := context.TODO() 要点: ...