Go 并发模型:Goroutine 与 Context¶
并发不是“开 goroutine 就完了”,更重要的是:如何停止它们、如何传递超时、如何避免泄漏。
1. 基本模式:工作池¶
jobs := make(chan Job)
for i := 0; i < 8; i++ {
go worker(i, jobs)
}
2. 用 Context 管理生命周期¶
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
建议:
- I/O 边界(HTTP、DB、RPC)一定传 ctx
- goroutine 内部定期检查
ctx.Done()
3. 典型陷阱¶
- channel 未关闭导致 goroutine 阻塞
- select 默认分支写错导致 busy loop
- 忘记 cancel 导致资源不释放