作用:用于在go协程中 传递上下文、超时、取消、传值
底层实现:是由互斥锁、channel、map来实现的
互斥锁:保护临界资源
channel: 用于信号通知,比如ctx.Done()
map: 保存父ctx下派生的所有子ctx, 父ctx关闭,子ctx都关闭
实现的接口
type Context interface {
Deadline() (deadline time.Time, ok bool)
Done() <-chan struct{
}
Err() error
Value(key interface{
}) interface{
}
}
空ctx
type emptyCtx int
func (*emptyCtx) Deadline() (deadline time.Time, ok bool) {
return
}
func (*emptyCtx) Done() <-chan struct{
} {
return nil
}
func (*emptyCtx) Err() error {
return nil
}
func (*emptyCtx) Value(key interface{
}) interface{
} {
return nil
}
cancel ctx
使用map保存所有子ctx,确保父ctx cancel后,子ctx也cancel
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
}
func