go 的context贯穿整个goroutine的运行控制的中枢,可以实现执行的生命周期的控制。
Context是一个接口,他派生了context.emptyCtx(TODO),cancelCtx,timeCtx,valueCtx,在parent关闭时,会逐一关闭子context。
cancelCtx结构体
type cancelCtx struct {
Context
mu sync.Mutex // protects following fields
done chan struct{} // created lazily, closed by first cancel call
children map[canceler]struct{} // set to nil by the first cancel call
err error // set to non-nil by the first cancel call
}
context.withCancel返回两个值,context和func,通过func可以控制关闭context,而context可以获取状态.