很多时候,我们会遇到这样的情况,上层与下层的goroutine需要同时取消,这样就涉及到了goroutine间的通信。在Go中,推荐我们以通信的方式共享内存,而不是以共享内存的方式通信。所以,就需要用到channl,但是,在上述场景中,如果需要自己去处理channl的业务逻辑,就会有很多费时费力的重复工作,因此,context出现了。
channlsnyc.Mutex
2. 基本介绍context
contextcontextcancelcontexttimerdeadlinecontextkey、valcontextemptyCtxemptyCtxcancelCtxtimerCtxtimerCtxvalueCtx
3. 源码分析3.1 Context 接口type Context interface { Deadline() (deadline time.Time, ok bool) Done() <-chan struct{} Err() error Value(key interface{}) interface{} } 复制代码
Deadline() :返回一个time.Time,表示当前Context应该结束的时间,ok则表示有结束时间
Done():返回一个只读chan,如果可以从该 chan 中读取到数据,则说明 ctx 被取消了
Err():返回 Context 被取消的原因
Value(key):返回key对应的value,是协程安全的
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 } 复制代码
emptyCtxContextBackgroundTODObackgroundtodo
var ( background = new(emptyCtx) todo = new(emptyCtx) ) func Background() Context { return background } func TODO() Context { return todo } 复制代码
BackgroundTODO
BackgroundTODO
2.3 cancelCtxcancelCtxcancelerContext
type canceler interface { cancel(removeFromParent bool, err error) Done() <-chan struct{} } 复制代码
其结构体如下:
type cancelCtx struct { // 直接嵌入了一个 Context,那么可以把 cancelCtx 看做是一个 Context Context mu sync.Mutex // protects following fields done atomic.Value // of 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 } 复制代码
WithCancelcancelCtx
func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { if parent == nil { panic("cannot create context from nil parent") } c := newCancelCtx(parent) propagateCancel(parent, &c) return &c, func() { c.cancel(true, Canceled) } } func newCancelCtx(parent Context) cancelCtx { return cancelCtx{Context: parent} } 复制代码
background
newCancelCtxcontext.cancelCtx
propagateCancel
func propagateCancel(parent Context, child canceler) { // 1.如果 parent ctx 是不可取消的 ctx,则直接返回 不进行关联 done := parent.Done() if done == nil { return // parent is never canceled } // 2.接着判断一下 父ctx 是否已经被取消 select { case <-done: // 2.1 如果 父ctx 已经被取消了,那就没必要关联了 // 然后这里也要顺便把子ctx给取消了,因为父ctx取消了 子ctx就应该被取消 // 这里是因为还没有关联上,所以需要手动触发取消 // parent is already canceled child.cancel(false, parent.Err()) return default: } // 3. 从父 ctx 中提取出 cancelCtx 并将子ctx加入到父ctx 的 children 里面 if p, ok := parentCancelCtx(parent); ok { p.mu.Lock() // double check 一下,确认父 ctx 是否被取消 if p.err != nil { // 取消了就直接把当前这个子ctx给取消了 // parent has already been canceled child.cancel(false, p.err) } else { // 否则就添加到 children 里面 if p.children == nil { p.children = make(map[canceler]struct{}) } p.children[child] = struct{}{} } p.mu.Unlock() } else { // 如果没有找到可取消的父 context。新启动一个协程监控父节点或子节点取消信号 atomic.AddInt32(&goroutines, +1) go func() { select { case <-parent.Done(): child.cancel(false, parent.Err()) case <-child.Done(): } }() } } 复制代码
上面的方法可能遇到以下几种情况:
parent.Done() == nilparentchildparentchildchildparentchildrenparentDone()parent.Done()child.Done()parent.Done()child.cancel
propagateCancelparentchildparentchild
func parentCancelCtx(parent Context) (*cancelCtx, bool) { done := parent.Done() // 如果 done 为 nil 说明这个ctx是不可取消的 // 如果 done == closedchan 说明这个ctx不是标准的 cancelCtx,可能是自定义的 if done == closedchan || done == nil { return nil, false } // 然后调用 value 方法从ctx中提取出 cancelCtx p, ok := parent.Value(&cancelCtxKey).(*cancelCtx) if !ok { return nil, false } // 最后再判断一下cancelCtx 里存的 done 和 父ctx里的done是否一致 // 如果不一致说明parent不是一个 cancelCtx pdone, _ := p.done.Load().(chan struct{}) if pdone != done { return nil, false } return p, true } 复制代码
chan struct{}
func (c *cancelCtx) Done() <-chan struct{} { d := c.done.Load() if d != nil { return d.(chan struct{}) } c.mu.Lock() defer c.mu.Unlock() d = c.done.Load() if d == nil { d = make(chan struct{}) c.done.Store(d) } return d.(chan struct{}) } var closedchan = make(chan struct{}) 复制代码
parentCancelCtx 其实就是判断 parent context 里面有没有一个 cancelCtx,有就返回,让子context可以“挂靠”到parent context 上,如果不是就返回false,不进行挂靠,自己新开一个 goroutine 来监听。
2.4 timerCtxtimerdeadline
type timerCtx struct { cancelCtx timer *time.Timer // Under cancelCtx.mu. deadline time.Time } func (c *timerCtx) Deadline() (deadline time.Time, ok bool) { return c.deadline, true } func (c *timerCtx) cancel(removeFromParent bool, err error) { c.cancelCtx.cancel(false, err) if removeFromParent { removeChild(c.cancelCtx.Context, c) } c.mu.Lock() if c.timer != nil { c.timer.Stop() c.timer = nil } c.mu.Unlock() } 复制代码
2.5 valueCtxvalueCtx 是多了 key、val 两个字段来存数据:
type valueCtx struct { Context key, val interface{} } 复制代码
取值查找的过程,实际上是一个递归查找的过程:
func (c *valueCtx) Value(key interface{}) interface{} { if c.key == key { return c.val } return c.Context.Value(key) } 复制代码
如果 key 和当前 ctx 中存的 value 一致就直接返回,没有就去 parent 中找。最终找到根节点(一般是 emptyCtx),直接返回一个 nil。所以用 Value 方法的时候要判断结果是否为 nil,类似于一个链表,效率是很低的,不建议用来传参数。
4. 使用建议在官方博客里,对于使用 context 提出了几点建议:
不要将 Context 塞到结构体里。直接将 Context 类型作为函数的第一参数,而且一般都命名为 ctx。
不要向函数传入一个 nil 的 context,如果你实在不知道传什么,标准库给你准备好了一个 context:todo。
不要把本应该作为函数参数的类型塞到 context 中,context 存储的应该是一些共同的数据。例如:登陆的 session、cookie 等。
同一个 context 可能会被传递到多个 goroutine,别担心,context 是并发安全的。