Go上下文context底层原理

4,931 阅读7分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第13天,点击查看活动详情

1. context 介绍

很多时候,我们会遇到这样的情况,上层与下层的goroutine需要同时取消,这样就涉及到了goroutine间的通信。在Go中,推荐我们以通信的方式共享内存,而不是以共享内存的方式通信。所以,就需要用到channl,但是,在上述场景中,如果需要自己去处理channl的业务逻辑,就会有很多费时费力的重复工作,因此,context出现了。

context是Go中用来进程通信的一种方式,其底层是借助channlsnyc.Mutex实现的。

2. 基本介绍

context的底层设计,我们可以概括为1个接口,4种实现与6个方法。

  • 1 个接口

    • Context 规定了context的四个基本方法
  • 4 种实现

    • emptyCtx 实现了一个空的context,可以用作根节点
    • cancelCtx 实现一个带cancel功能的context,可以主动取消
    • timerCtx 实现一个通过定时器timer和截止时间deadline定时取消的context
    • valueCtx 实现一个可以通过 key、val 两个字段来存数据的context
  • 6 个方法

    • Background 返回一个emptyCtx作为根节点
    • TODO 返回一个emptyCtx作为未知节点
    • WithCancel 返回一个cancelCtx
    • WithDeadline 返回一个timerCtx
    • WithTimeout 返回一个timerCtx
    • WithValue 返回一个valueCtx

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,是协程安全的

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

emptyCtx实现了空的Context接口,其主要作用是为BackgroundTODO这两个方法都会返回预先初始化好的私有变量 background 和 todo,它们会在同一个 Go 程序中被复用:

var (
    background = new(emptyCtx)
    todo       = new(emptyCtx) 
)

func Background() Context {
    return background
}
func TODO() Context {
	return todo
}

BackgroundTODO在实现上没有区别,只是在使用语义上有所差异:

  • Background是上下文的根节点;
  • TODO应该仅在不确定应该使用哪种上下文时使用;

2.3 cancelCtx

cancelCtx实现了canceler接口与Context接口:

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
}

我们可以使用WithCancel的方法来创建一个cancelCtx:

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

上面的方法,我们传入一个父 Context(这通常是一个 background,作为根节点),返回新建的 context,并通过闭包的形式,返回了一个 cancel 方法。

newCancelCtx将传入的上下文包装成私有结构体context.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() == nil,也就是 parent 不会触发取消事件时,当前函数会直接返回;

  • 当 child 的继承链包含可以取消的上下文时,会判断 parent 是否已经触发了取消信号;

    • 如果已经被取消,child 会立刻被取消;
    • 如果没有被取消,child 会被加入 parent 的 children 列表中,等待 parent 释放取消信号;
  • 当父上下文是开发者自定义的类型、实现了 context.Context 接口并在 Done() 方法中返回了非空的管道时;

    • 运行一个新的 Goroutine 同时监听 parent.Done() 和 child.Done() 两个 Channel;
    • 在 parent.Done() 关闭时调用 child.cancel 取消子上下文;

propagateCancel 的作用是在 parent 和 child 之间同步取消和结束的信号,保证在 parent 被取消时,child 也会收到对应的信号,不会出现状态不一致的情况。

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
}

ancelCtx 的 done 方法会返回一个 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 timerCtx

timerCtx 内部不仅通过嵌入 cancelCtx 的方式承了相关的变量和方法,还通过持有的定时器 timer 和截止时间 deadline 实现了定时取消的功能:

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 valueCtx

valueCtx 是多了 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 提出了几点建议:

  1. 不要将 Context 塞到结构体里。直接将 Context 类型作为函数的第一参数,而且一般都命名为 ctx。
  2. 不要向函数传入一个 nil 的 context,如果你实在不知道传什么,标准库给你准备好了一个 context:todo。
  3. 不要把本应该作为函数参数的类型塞到 context 中,context 存储的应该是一些共同的数据。例如:登陆的 session、cookie 等。
  4. 同一个 context 可能会被传递到多个 goroutine,别担心,context 是并发安全的。