Context用于协调并发任务的取消与超时,通过Done()通道传递信号,结合WithTimeout可控制单个或多个任务的执行时长,避免资源泄漏。

在go语言中,context 是控制并发任务生命周期的核心机制。当需要对多个并发任务设置超时、取消或传递请求范围的值时,context 提供了简洁而强大的支持。特别是在网络请求、数据库查询或批量处理等场景中,使用 context 控制超时能有效避免资源泄漏和响应延迟。
理解 Context 的基本作用
Context 不是用来“做”事情的工具,而是用来“通知”事情是否该停止。它通过传递信号的方式协调多个 goroutine 的行为:
- Done():返回一个只读通道,当该通道被关闭时,表示上下文已被取消或超时
- Err():返回取消的原因,比如 context.Canceled 或 context.DeadlineExceeded
- WithCancel / WithTimeout / WithDeadline:用于派生新的 context 实例
最常用的是 context.WithTimeout,它允许你设定一个最大执行时间,超过这个时间后自动触发取消信号。
使用 WithTimeout 控制单个任务超时
假设我们有一个耗时操作(如http请求),希望最多等待2秒,否则就放弃:
立即学习“go语言免费学习笔记(深入)”;
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() <p>req, _ := http.NewRequest("GET", "<a href="https://www.php.cn/link/c19fa3728a347ac2a373dbb5c44ba1c2">https://www.php.cn/link/c19fa3728a347ac2a373dbb5c44ba1c2</a>", nil) req = req.WithContext(ctx) // 将 ctx 绑定到请求</p><p>client := &http.Client{} resp, err := client.Do(req) if err != nil { if err == context.DeadlineExceeded { fmt.Println("请求超时") } else { fmt.Printf("请求出错: %vn", err) } return } defer resp.Body.Close() fmt.Println("响应状态:", resp.Status)
这里的关键是将 context 绑定到 HTTP 请求上,client.Do 会监听 ctx.Done(),一旦超时就会中断连接。
控制多个并发任务的集体超时
更复杂的场景下,可能需要同时发起多个异步任务,并整体控制它们的最长执行时间。可以结合 sync.WaitGroup 和 context 实现安全的并发控制:
ctx, cancel := context.WithTimeout(context.Background(), 1500*time.Millisecond) defer cancel() <p>urls := []string{ "<a href="https://www.php.cn/link/5f69e19efaba426d62faeab93c308f5c">https://www.php.cn/link/5f69e19efaba426d62faeab93c308f5c</a>", "<a href="https://www.php.cn/link/ef246753a70fce661e16668898810624">https://www.php.cn/link/ef246753a70fce661e16668898810624</a>", "<a href="https://www.php.cn/link/5f69e19efaba426d62faeab93c308f5c">https://www.php.cn/link/5f69e19efaba426d62faeab93c308f5c</a>", }</p><p>var wg sync.WaitGroup for _, url := range urls { wg.Add(1) go func(u string) { defer wg.Done()</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;"> req, _ := http.NewRequest("GET", u, nil) req = req.WithContext(ctx) client := &http.Client{} resp, err := client.Do(req) if err != nil { select { case <-ctx.Done(): // 超时或取消导致的错误,统一处理 return default: fmt.Printf("请求失败 %s: %vn", u, err) } return } fmt.Printf("成功获取: %s, 状态: %sn", u, resp.Status) resp.Body.Close() }(url)
}
wg.Wait() fmt.Println(“所有任务完成或已超时”)
在这个例子中,即使某个请求因超时被取消,其他仍在运行的任务也会收到相同的 context 取消信号,从而实现整体控制。
避免 Goroutine 泄漏的小技巧
使用 context 时容易忽略的一点是:即使父 context 已取消,子 goroutine 如果没有正确监听 Done() 信号,仍可能继续运行,造成 goroutine 泄漏。
确保你在每个协程中都检查 ctx.Done():
select { case <-time.After(3 * time.Second): fmt.Println("任务完成") case <-ctx.Done(): fmt.Println("任务被取消:", ctx.Err()) return }
对于自定义长时间任务,应周期性地检查 ctx.Err() 是否非 nil,及时退出。
基本上就这些。合理使用 context.WithTimeout 配合 goroutine 和 channel,就能写出健壮的并发程序。关键是让所有下游操作都能感知到同一个取消信号,形成完整的控制链路。