简介
在golang中context出现的频率极高,例如有多个goroutine来处理一个操作,这个操作有超时时间,当超时时间到了之后,如何通知这个操作的所有goroutine都退出。或者在操作的过程中有一个goroutine遇到异常需要退出,如何通知其他的goroutine也退出该操作? context就可以很好的解决以上问题。
Go服务器的每个请求都有自己的goroutine,而有的请求为了提高性能,会经常启动额外的goroutine处理请求,当该请求被取消或超时,为了防止资源泄露,该请求上的所有goroutines应该退出。那么context来了,它对该请求上的所有goroutines进行约束,然后进行取消信号,超时等操作。
context优点就是简洁的管理goroutines的生命周期。
源码分析
Context接口
type Context interface {Deadline() (deadline time.Time, ok bool)Done() <-chan struct{}Err() errorValue(key interface{}) interface{}}
Dealine
返回当前上下文的截至时间,即该上下文应该被取消的时间,如果没有设置超时时间,则返回的ok为false
Done
在Context被取消或超时时会close当前监听的channel,close的channel可以作为广播通知,告诉context相关的函数要停止当前工作然后退出。创建Context时会返回CancelFunc函数,调用CancelFunc函数以及到了超时时间,会关闭Done()方法监听的channel,所以Done()需要放到select中。
父Context取消时,其子Context也会被取消。但是子Context取消时,其父Context不会被取消。
Err
如果Done未关闭,则Err返回nil,如果Done已关闭,则返回非空的error解释原因。
Value
通过key获取该key在上下文中关联的值,如果该key没有关联的值,则返回nil,多次调用同一个key,返回的结果是一样的。
TODO & Background
TODO() & Background() 都是返回empty,empty是空的Context,但是实现了Context的接口。emptyCtx没有超时时间,不能被取消,也不能存储任何额外信息,所以emptyCtx常用来作为Context的根节点。
type emptyCtx intfunc (*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}func (e *emptyCtx) String() string {switch e {case background:return "context.Background"case todo:return "context.TODO"}return "unknown empty Context"}var (background = new(emptyCtx)todo = new(emptyCtx))func Background() Context {return background}func TODO() Context {return todo}
WithCancel
拷贝父context,并赋予一个新的Done channel。返回这个context以及cancel函数。
当以下情况发生其中之一时,这个context会被取消:
- cancel函数被调用
- 父context的Done channel被关闭
所以在写代码的时候,如果在当前context已经完成逻辑处理,则应该调用cancel函数来通知其他协程释放资源。
可以看到主要是两个方法:newCancelCtx和propagateCancelfunc WithCancel(parent Context) (ctx Context, cancel CancelFunc) {c := newCancelCtx(parent)propagateCancel(parent, &c)return &c, func() { c.cancel(true, Canceled) }// 注意return的是&c}
newCancelCtx
是用父context初始化一个cancelCtx对象,cancelCtx是context的一个实现类:func newCancelCtx(parent Context) cancelCtx {return cancelCtx{Context: parent}}
type cancelCtx struct {Context //指向父context的引用mu sync.Mutex // 锁用来保护下面几个字段done chan struct{} // 用来通知其他,代表这个context已经结束了children map[canceler]struct{} // 里面保存了所有子contex的联系,用来在结束当前context的时候,结束所有子context。这个字段cancel之后,设为nil。err error // cancel之后,就不是nil了。}func (c *cancelCtx) Value(key interface{}) interface{} {if key == &cancelCtxKey {return c}return c.Context.Value(key) // 一直往上找,最后找到根(todo、background)还没有就返回nil}func (c *cancelCtx) Done() <-chan struct{} {c.mu.Lock()if c.done == nil {c.done = make(chan struct{})}d := c.donec.mu.Unlock()return d}func (c *cancelCtx) Err() error {c.mu.Lock()err := c.errc.mu.Unlock()return err}func (c *cancelCtx) cancel(removeFromParent bool, err error) {if err == nil {//任何context关闭后,都需要一个错误来给字段err赋值来表明结束的原因,不传入err是不行的panic("context: internal error: missing cancel error")}c.mu.Lock()//加锁if c.err != nil {//如果错误已经有了,说明这个context已经结束了,就不用cancel了c.mu.Unlock()return // already canceled}c.err = err//赋值错误原因if c.done == nil {c.done = closedchan //这个字段延迟加载,closedchan是一个context包中的量,一个已经关闭的channel,所有context都复用这个关闭的channel} else {//当然如果已经加载了,则直接关闭。那是啥时候加载的呢?当然是在这个context还没结束的时候,有人调用了Done()方法,所以是延迟加载。close(c.done)}for child := range c.children {//结束所有子context。之前每次的propagateCancel总算派上用场了。child.cancel(false, err)}c.children = nilc.mu.Unlock()if removeFromParent {//如果需要的话,切断当前context和父context的联系。就是从父context的children map里移除嘛。当然如果fucontext不是cancelCtx,就没事咯removeChild(c.Context, c)}}
propagateCancel
propagateCancel顾名思义,就是传播cancel,就是保证父context结束的时候,我们用WithCancel得到的子context能够跟着结束。
func propagateCancel(parent Context, child canceler) {if parent.Done() == nil {//父context如果永远不能取消,直接返回,不用关联。return}if p, ok := parentCancelCtx(parent); ok {//因为传入的父context类型是Context接口,不一定是CancelCtx,所以如果要关联,则先判断类型p.mu.Lock()//加锁,保护字段childrenif p.err != nil {//说明父context已经结束了,也别做其他操作了,直接取消这个子context吧child.cancel(false, p.err)} else {//没有结束,就在父context里加上子context的联系,用来之后取消子context用if p.children == nil {p.children = make(map[canceler]struct{})}p.children[child] = struct{}{}}p.mu.Unlock()} else {//因为传入的父context类型不是CancelCtx,则不一定有children字段的,只能起一个协程来监听父context的Done,如果Done关闭了,就可以取消子context了。go func() {select {case <-parent.Done():child.cancel(false, parent.Err())case <-child.Done()://为了避免子context比父context先取消,造成这个监听协程泄露,这里加了这样一个case}}()}}
再来看一下,WithCancel的return &c, func() { c.cancel(true, Canceled) }中的c.cancel(true, Canceled)或是(child.cancel(false, parent.Err()))到底干了啥:
因为c是类型cancelCtx,其有一个方法是cancel,这个方法其实是实现的cancel接口的方法,这在前面的cancelCtx的字段children map[canceler]struct{}中,可以看到这个map的key就是这个接口。
canceler
这个接口包含了两个方法,实现类有cancelCtx 和timerCtx。
看下*cancelCtx的实现,这个方法的作用是关闭cancelCtx对象的done channel(代表这个context结束了),然后cancel这个context的所有子context,如果必要的话并切断这个context和其父context的关系(其实就是这个context的子context通过propagateCancel关联上的):
type canceler interface {cancel(removeFromParent bool, err error)Done() <-chan struct{}}
WithDeadline
拷贝父context,并设置截止时间为d。如果父context截止时间小于d,则使用父context的截止时间。
当以下情况发生其中之一时,这个context会被取消:
- 截止时间到
- 返回发cancel函数被调用
- 父context的Done channel被关闭
func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) {if cur, ok := parent.Deadline(); ok && cur.Before(d) {//如果当前的Deadline比父Deadline晚,则用父Deadline,直接WithCancel就好了,因为父Deadline到了结束了,这个context也就结束了。WithCancel是为了返回一个cancelfunc。return WithCancel(parent)}c := &timerCtx{//可以看到,timerCtx其实就是包装了一下newCancelCtx,newCancelCtx在前文已经介绍了,这里看上去就简单多了。cancelCtx: newCancelCtx(parent),deadline: d,}propagateCancel(parent, c)//propagateCancel在前文介绍过了,这里就是传播cancel嘛。dur := time.Until(d)if dur <= 0 {//时间到了,就直接可以cancel了c.cancel(true, DeadlineExceeded)return c, func() { c.cancel(false, Canceled) }}c.mu.Lock()defer c.mu.Unlock()if c.err == nil {//如果还没取消,就设置个定时器,AfterFunc函数就是说,在时间dur之后,执行func,即cancel。c.timer = time.AfterFunc(dur, func() {c.cancel(true, DeadlineExceeded)})}return c, func() { c.cancel(true, Canceled) }}
WithTimeout
一定时间后超时,自动取消context以及其子context。
其实就是用了WithDeadline,只不过截止日期写的是当前时间+timeoutfunc WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {return WithDeadline(parent, time.Now().Add(timeout))}
WithValue
拷贝父context,并在context中设置键值。这样就可以从context中取出数据来使用。
需要注意的是,用context 的value来传递请求维度的数据,不要用来传递函数的可选参数。
传递数据使用的key,不应该是string或者其他任何go的内置类型,而是应该使用用户自定义的类型作为key。这样能避免冲突。
key必须是可比较的,意思是可以用来判断是否是同一个key,即相等。
导出的context key的静态类型应该用指针或者Interface
看到返回了一个valueCtx对象func WithValue(parent Context, key, val interface{}) Context {if key == nil {//没有key肯定是不行的辣panic("nil key")}if !reflectlite.TypeOf(key).Comparable() {//key不可比较也是不行的辣,Comparable()是接口Type的一个方法,不可比较,那么取value的时候,咋知道你到底想取啥panic("key is not comparable")}return &valueCtx{parent, key, val}}
好家伙,原来是包装了一个context,加俩字段key和value。这还了得,那如果多WithValue几次,那不得串成长长的一个链。可以看到这里每WithValue一次,就多一个节点,这个链可够长,取value就是向上遍历这个context链了嘛。type valueCtx struct {Contextkey, val interface{}}
这个向上遍历的链,如果一直找不到key呢,就会终止在顶层context:background或者todofunc (c *valueCtx) Value(key interface{}) interface{} {if c.key == key {//key的可比性就是用在这里的return c.val}return c.Context.Value(key)//如果当前valueCtx里没有找到这个key,就向上遍历链,直到找到为止}
然后获取Value,他们俩的value都是nilvar (background = new(emptyCtx)todo = new(emptyCtx))func Background() Context {return background}func TODO() Context {return todo}
func (*emptyCtx) Value(key interface{}) interface{} {return nil}
