Golang的Context介绍及其源码分析

简介

在Go服务中,对于每个请求,都会起一个协程去处理。在处理协程中,也会起很多协程去访问资源,比如数据库,比如RPC,这些协程还需要访问请求维度的一些信息比如说请求方的身份,授权信息等等。当一个请求被取消或者超时的时候,其他所有协程都应该立即被取消以释放资源。
Golang的context包就是用来传递请求维度的数据、信号、超时给处理该请求的所有协程的。在处理请求的方法调用链中,必须传递context,当然也可以使用WithCancel, WithDeadline, WithTimeout或者WithValue去派生出子context来传递。当一个context被取消的时候,其派生出的所有子context都会被取消。
包的介绍

Context

在context包中,最核心的就是Context接口,其结构如下:

type Context interface {
   Deadline() (deadline time.Time, ok bool)
   Done() <-chan struct{}
   Err() error
   Value(key interface{}) interface{}
}

一个context可以传递一个截止时间、一个取消信号和其他值。其方法是可以被多个协程同时调用的。

  • Deadline() (deadline time.Time, ok bool)
    返回一个截止时间,代表这个context要到达截止时间会被取消。返回的ok如果是false表示没有设置截止时间,即不会超时。

  • Done() <-chan struct{}
    返回一个已经关闭的channel,表示这个context被取消了。如果这个context永远不能被取消的话,则返回nil。
    一般Done的放在select语句中使用,如:

func Stream(ctx context.Context, out chan<- Value) error {//Stream函数就是用来不断产生值并把值发送到out channel里,直到发生DoSomething发生错误或者ctx.Done关闭
   for {
      v, err := DoSomething(ctx)//DoSomething用来产生值
      if err != nil {
         return err
      }
      select {
      case <-ctx.Done(): //ctx.Done关闭
         return ctx.Err()
      case out <- v://将产生的值发送出去
      }
   }
}
  • Err() error
    返回的err是用来说明这个context取消的原因。如果Done channel还没有关闭,Err()返回nil。
    一般包自带的两个错误是:取消和超时
var Canceled = errors.New("context canceled")
var DeadlineExceeded error = deadlineExceededError{}
  • Value(key interface{}) interface{}
    返回保存在context中的key对应的值,如果不存在则返回nil。

WithCancel

func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
拷贝父context,并赋予一个新的Done channel。返回这个context以及cancel函数。
当以下情况发生其中之一时,这个context会被取消:

  • cancel函数被调用
  • 父context的Done channel被关闭
    所以在写代码的时候,如果在当前context已经完成逻辑处理,则应该调用cancel函数来通知其他协程释放资源。
    使用示例:
func main() {
   //gen函数用来产生一个不断生产数字到channel的协程,并返回channel
   gen := func(ctx context.Context) <-chan int {
      dst := make(chan int)
      n := 1
      go func() {
         for {
            select {
            case <-ctx.Done():
               return //每一次生产数字都检查context是否已经被取消,防止协程泄露
            case dst <- n:
               n++
            }
         }
      }()
      return dst
   }

   ctx, cancel := context.WithCancel(context.Background())
   defer cancel() //在消费完生产的数字之后,调用cancel函数来取消context,以此通知其他协程

   for n := range gen(ctx) { //只消费5个数字
      fmt.Println(n)
      if n == 5 {
         break
      }
   }
}

源码分析

这个方法是怎么实现的呢?让我们来看一下源码:

func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
   c := newCancelCtx(parent)
   propagateCancel(parent, &c)
   return &c, func() { c.cancel(true, Canceled) }
}

可以看到主要是两个方法:newCancelCtx和propagateCancel
newCancelCtx是用父context初始化一个cancelCtx对象,cancelCtx是context的一个实现类:

func newCancelCtx(parent Context) cancelCtx {
   return cancelCtx{Context: parent}
}

看下这个newCancelCtx的结构,newCancelCtx其实是Context接口的一个实现类:

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了。
}

propagateCancel顾名思义,就是传播cancel,就是保证父context结束的时候,我们用WithCancel得到的子context能够跟着结束。
然后返回这个新建的cancelCtx对象和一个CancelFunc。CancelFunc是一个函数,内部是调用了cancelCtx对象的cancel方法,这个方法的作用是关闭cancelCtx对象的done channel(代表这个context结束了),然后cancel这个context的所有子context,如果必要的话并切断这个context和其父context的关系(其实就是这个context的子context通过propagateCancel关联上的)。
看下propagateCancel的内部:

func propagateCancel(parent Context, child canceler) {
   if parent.Done() == nil {//父context如果永远不能取消,直接返回,不用关联。
      return
   }
   if p, ok := parentCancelCtx(parent); ok {//因为传入的父context类型是Context接口,不一定是CancelCtx,所以如果要关联,则先判断类型
      p.mu.Lock()//加锁,保护字段children
      if 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)到底干了啥:
因为c是类型cancelCtx,其有一个方法是cancel,这个方法其实是实现的cancel接口的方法,这在前面的cancelCtx的字段children map[canceler]struct{}中,可以看到这个map的key就是这个接口。

type canceler interface {
   cancel(removeFromParent bool, err error)
   Done() <-chan struct{}
}

这个接口包含了两个方法,实现类有*cancelCtx 和*timerCtx。
看下*cancelCtx的实现,这个方法的作用是关闭cancelCtx对象的done channel(代表这个context结束了),然后cancel这个context的所有子context,如果必要的话并切断这个context和其父context的关系(其实就是这个context的子context通过propagateCancel关联上的):

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 = nil
   c.mu.Unlock()

   if removeFromParent {//如果需要的话,切断当前context和父context的联系。就是从父context的children  map里移除嘛。当然如果fucontext不是cancelCtx,就没事咯
      removeChild(c.Context, c)
   }
}

这样就介绍完源码了,看起来不错哦。

WithDeadline

func WithDeadline(parent Context, d time.Time) (Context, CancelFunc)
拷贝父context,并设置截止时间为d。如果父context截止时间小于d,则使用父context的截止时间。
当以下情况发生其中之一时,这个context会被取消:

  • 截止时间到
  • 返回发cancel函数被调用
  • 父context的Done channel被关闭
    使用示例
func main() {
   d := time.Now().Add(50 * time.Millisecond)
   ctx, cancel := context.WithDeadline(context.Background(), d)

   //即使ctx已经设置了截止时间,会自动过期,但是最好还是在不需要的时候主动调用cancel函数
   defer cancel()

   select {
   case <-time.After(1 * time.Second):
      fmt.Println("overslept")
   case <-ctx.Done():     //这个会先到达
      fmt.Println(ctx.Err())
   }
}

源码分析

看一下WithDeadline的实现是怎么样的:

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) }
}

理解了WithCancel的实现,这个WithCancel的源码还是很简单的。

WithTimeout

func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
一定时间后超时,自动取消context以及其子context。
其实就是用了WithDeadline,只不过截止日期写的是当前时间+timeout

func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
   return WithDeadline(parent, time.Now().Add(timeout))
}

使用示例是一样的

func main() {
   ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
   defer cancel()

   select {
   case <-time.After(1 * time.Second):
      fmt.Println("overslept")
   case <-ctx.Done():
      fmt.Println(ctx.Err())
   }

}

源码分析

看WithDeadline的源码就好。

WithValue

func WithValue(parent Context, key, val interface{}) Context
拷贝父context,并在context中设置键值。这样就可以从context中取出数据来使用。
需要注意的是,用context 的value来传递请求维度的数据,不要用来传递函数的可选参数。
传递数据使用的key,不应该是string或者其他任何go的内置类型,而是应该使用用户自定义的类型作为key。这样能避免冲突。
key必须是可比较的,意思是可以用来判断是否是同一个key,即相等。
导出的context key的静态类型应该用指针或者Interface
使用示例

func main() {
   type favContextKey string //定义一个自定义类型作为key

   f := func(ctx context.Context, k interface{}) {//判断key是否存在以及值的函数
      if v := ctx.Value(k); v != nil {
         fmt.Println("found value:", v)
         return
      }
      fmt.Println("key not found:", k)
   }

   k := favContextKey("language")
   ctx := context.WithValue(context.Background(), k, "Go") //使用自定义类型作为key

   f(ctx, k) //found value: Go
   f(ctx, favContextKey("color")) //key not found: color

   ctx2 := context.WithValue(ctx, "language", "Java") //使用string,试图覆盖之前的key对应的值
   f(ctx2, k) //found value: Go ,并没有被覆盖
   f(ctx2, "language") //found value: Java ,两个key互相独立
}

而在使用context来存储key-value的时候,最好的方式是不导出key,key只在包内可访问,在包内定义,然后包提供安全的访问方法来保存key-value和取key-value。如:

type User struct {// User是我们要作为value保存在contex里的值
   //自定义字段
}

type key int //key是我们定义在包内的key类型,这样不会与其他包的冲突

var userKey key//key类型的变量,用作context里的key。

// NewContext方法用来将value存入context
func NewContext(ctx context.Context, u *User) context.Context {
   return context.WithValue(ctx, userKey, u)
}
// FromContext用来取value
func FromContext(ctx context.Context) (*User, bool) {
   u, ok := ctx.Value(userKey).(*User)
   return u, ok
}

源码分析

看一下WithValue的实现是咋样的:

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}
}

看到返回了一个valueCtx对象,这是个啥,康康:

type valueCtx struct {
   Context
   key, val interface{}
}

好家伙,原来是包装了一个context,加俩字段key和value。这还了得,那如果多WithValue几次,那不得串成长长的一个链。可以看到这里每WithValue一次,就多一个节点,这个链可够长,取value就是向上遍历这个context链了嘛。来康康取值方法Value()的实现,其实我们知道Value(key interface{}) interface{}是context接口的一个方法,所以我们看下这个在valueCtx结构中的实现:

func (c *valueCtx) Value(key interface{}) interface{} {
   if c.key == key {//key的可比性就是用在这里的
      return c.val
   }
   return c.Context.Value(key)//如果当前valueCtx里没有找到这个key,就向上遍历链,直到找到为止
}

这个向上遍历的链,如果一直找不到key呢,就会终止在顶层context:background或者todo
看一哈:

var (
   background = new(emptyCtx)
   todo       = new(emptyCtx)
)
func Background() Context {
   return background
}
func TODO() Context {
   return todo
}

是滴,context.Background()和context.TODO()就造了这么个玩意儿,emptyCtx类型的一个对象,emptyCtx是什么东西呢,来截取一小部分康康:

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
}

好家伙是个惊天骗局,本质上只是个int,居然还实现了context接口。
其Value返回nil,破案了。

Background

func Background() Context
返回一个非nil非空的context,永远不会被取消,也没有value,没有deadline。一般用于main函数里,或者初始化,用作顶层的context。

TODO

func TODO() Context
返回一个非nil非空的context。当不知道用什么context,或者还不使用context但是有这个入参的时候,可以用这个。

posted @ 2020-04-20 20:41  Chaunceeeeeeeeey  阅读(380)  评论(0编辑  收藏  举报