context是goland中的经典工具,主要在异步场景中实现并发协调以及对goroutine的生命周期的控制,除此之外,context还兼有一定的数据储存能力。
主要内容有一个接口context,四个实现类emptyCtx,cancelCtx,timerCtx,valueCtx,六个方法Background、TODO、WithCancel、WithDeadline、WithTimeout、WithValue
1 核心数据结构
1.1 context.Context
type Context interface {
Deadline() (deadline time.Time, ok bool)
Done() <-chan struct{}
Err() error
Value(key any) any
}
Context是一个接口,定义了四个核心API:
- Deadline():返回context的过期时间
- Done():返回context中的channel,标识context是否结束
- Err():返回context结束的错误,比如是cancel错误或者是done错误
- Value():返回context中对应的key的值
1.2 相关错误 error
// Canceled is the error returned by Context.Err when the context is canceled.
var Canceled = errors.New("context canceled")
// DeadlineExceeded is the error returned by Context.Err when the context's
// deadline passes.
var DeadlineExceeded error = deadlineExceededError{}
type deadlineExceededError struct{}
func (deadlineExceededError) Error() string { return "context deadline exceeded" }
func (deadlineExceededError) Timeout() bool { return true }
func (deadlineExceededError) Temporary() bool { return true }
2 第一个实现类 emptyCtx
2.1 具体实现
// An emptyCtx is never canceled, has no values, and has no deadline. It is not
// struct{}, since vars of this type must have distinct addresses.
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 any) any {
return nil
}
- emptyCtx是一个空的context,本质上就是一个整形
- DeadLine方法返回一个time.Time的默认值(0001-01-01 00:00:00 +0000 UTC)以及false的flag,标识当前context不存在过期时间
- Done方法返回一个nil值,用户无论往nil中写入或者读取数据都会陷入阻塞
- Err方法返回的错误为nil
- Value方法返回一个nil
总结:官方实现的空白纸,不能cancel,没有value,也没有过期时间deadline,也没错误
2.2 context.Background() 和 context.TODO()
var (
background = new(emptyCtx)
todo = new(emptyCtx)
)
// Background returns a non-nil, empty Context. It is never canceled, has no
// values, and has no deadline. It is typically used by the main function,
// initialization, and tests, and as the top-level Context for incoming
// requests.
func Background() Context {
return background
}
// TODO returns a non-nil, empty Context. Code should use context.TODO when
// it's unclear which Context to use or it is not yet available (because the
// surrounding function has not yet been extended to accept a Context
// parameter).
func TODO() Context {
return todo
}
这两个方法本质都是返回一个emptyCtx对象,但是,官方有明确指出,Background返回一个非零的空上下文。它永远不会被取消,没有值,没有截止日期,通常用于main函数使用初始化和测试,并作为传入的顶级上下文请求。而TODO就跟这个名字一样,在不清楚使用哪一种类型的context或者它还不可用(因为周围函数尚未拓展为接受上下文参数)
3 第二个实现类 cancelCtx
3.1 数据结构
// A cancelCtx can be canceled. When canceled, it also cancels any children
// that implement canceler.
type cancelCtx struct {
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
}
// A canceler is a context type that can be canceled directly. The
// implementations are *cancelCtx and *timerCtx.
type canceler interface {
cancel(removeFromParent bool, err error)
Done() <-chan struct{}
}
- Context:内嵌了一个Context作为其父context。因为emptyCtx是鼻祖,所以,cancelCtx必然是某个context的子context;
- mu:内置了一把锁,用来协调并发场景下的资源获取
- done:实际类型为chan struct{},用来反映cancelCtx生命周期的通道,使用懒惰方式创建,第一次调用cancel时关闭
- children:指向cancelCtx的所有子context
- err:记录当前cancelCtx关闭的错误
- 子类canceler:只需要实现cancel和Done这两个方法(父类cancelCtx只关注子类的这两个方法,责任集中,边界分明),具体的实现类有cancelCtx和timerCtx
3.2 Deadline方法
cancelCtx没有实现该方法,仅是内嵌了一个带有Deadline方法的Context接口,因此直接调用会报错。
3.3 Done方法
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{})
}
- 读取cancelCtx的done看看chan存不存在,存在就直接返回,不存在就加锁准备创建chan
- 加锁后,再次检测chan是否存在,若存在就直接返回,不存在就创建一个chan并存储到cancelCtx的done
3.4 Err方法
func (c *cancelCtx) Err() error {
c.mu.Lock()
err := c.err
c.mu.Unlock()
return err
}
- 加锁
- 读取cancelCtx的终止错误
- 解锁
- 返回错误
3.5 Value方法
func (c *cancelCtx) Value(key any) any {
if key == &cancelCtxKey {
return c
}
return value(c.Context, key)
}
// &cancelCtxKey is the key that a cancelCtx returns itself for.
var cancelCtxKey int
- 此处先判断key == &cancelCtxKey,主要的用途就是判断当前的context是否是cancelCtx类型,因为cancelCtxKey是内部声明的一个变量,所以必然在某处有调用(下面介绍)
- 不是cancelCtx类型就到value方法接着判断类型返回结果(value方法后面ValueCtx介绍)
3.6 context.WithCancel()
// A CancelFunc tells an operation to abandon its work.
// A CancelFunc does not wait for the work to stop.
// A CancelFunc may be called by multiple goroutines simultaneously.
// After the first call, subsequent calls to a CancelFunc do nothing.
type CancelFunc func()
// WithCancel returns a copy of parent with a new Done channel. The returned
// context's Done channel is closed when the returned cancel function is called
// or when the parent context's Done channel is closed, whichever happens first.
//
// Canceling this context releases resources associated with it, so code should
// call cancel as soon as the operations running in this Context complete.
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) }
}
var Canceled = errors.New("context canceled")
- 检验父context - parent非空
- 注入父context构造一个新的cancelCtx
- propagateCancel方法用来保证父context-parent终止时,这个子类c也会被补刀终止
- 将cancelCtx返回,连带一个用以终止该cancelCtx的闭包函数(闭包函数Go 语言闭包详解 - 掘金 (juejin.cn))
3.6.1 newCancelCtx()
// newCancelCtx returns an initialized cancelCtx.
func newCancelCtx(parent Context) cancelCtx {
return cancelCtx{Context: parent}
}
- 注入父context,返回一个新的cancelCtx
3.6.2 propagateCancel()
// propagateCancel arranges for child to be canceled when parent is.
func propagateCancel(parent Context, child canceler) {
done := parent.Done()
if done == nil {
return // parent is never canceled
}
select {
case <-done:
// parent is already canceled
child.cancel(false, parent.Err())
return
default:
}
if p, ok := parentCancelCtx(parent); ok {
p.mu.Lock()
if p.err != nil {
// parent has already been canceled
child.cancel(false, p.err)
} else {
if p.children == nil {
p.children = make(map[canceler]struct{})
}
p.children[child] = struct{}{}
}
p.mu.Unlock()
} else {
atomic.AddInt32(&goroutines, +1)
go func() {
select {
case <-parent.Done():
child.cancel(false, parent.Err())
case <-child.Done():
}
}()
}
}
propageteCancel方法,就是用来传递父子context之间的cancel事件,具体流程如下:
- 如果parent是不可被cancel类型(如emptyCtx),则直接返回
- 如果parent已经被cancel,那就直接给它的子context补刀终止,以parent的err为子context的err
- 如果parent是cancelCtx类型,就加锁,然后把child添加到parent的child map中
- 如果parent不是cancelCtx类型,就启动一个协程,通过多路复用的方式监控parent和child的状态,如果parent终止,立刻给子context补刀终止,并传递parent的err给子context,如果是child终止就不需要操作
接着看parentCancelCtx是怎么校验parent是cancelCtx类型的:(跟上面的3.5的value方法呼应)
// &cancelCtxKey is the key that a cancelCtx returns itself for.
var cancelCtxKey int
// parentCancelCtx returns the underlying *cancelCtx for parent.
// It does this by looking up parent.Value(&cancelCtxKey) to find
// the innermost enclosing *cancelCtx and then checking whether
// parent.Done() matches that *cancelCtx. (If not, the *cancelCtx
// has been wrapped in a custom implementation providing a
// different done channel, in which case we should not bypass it.)
func parentCancelCtx(parent Context) (*cancelCtx, bool) {
done := parent.Done()
if done == closedchan || done == nil {
return nil, false
}
p, ok := parent.Value(&cancelCtxKey).(*cancelCtx)
if !ok {
return nil, false
}
pdone, _ := p.done.Load().(chan struct{})
if pdone != done {
return nil, false
}
return p, true
}
- 如果parent的done channel已经关闭或者是不会被cancel的类型,就返回 false
- 如果parent是cancelCtx类型,那么此处的parent.Value(&cancelCtxKey)调用的必然就是cancelCtx的Value方法,所以就会直接返回cancelCtx也就是parent本身(不理解就回去看3.5),如果不是cancelCtx类型就返回false
- double check此处再次确认parent是否被cancel,没有就返回true
3.6.3 cancelCtx.cancel()
// cancel closes c.done, cancels each of c's children, and, if
// removeFromParent is true, removes c from its parent's children.
func (c *cancelCtx) cancel(removeFromParent bool, err error) {
if err == nil {
panic("context: internal error: missing cancel error")
}
c.mu.Lock()
if c.err != nil {
c.mu.Unlock()
return // already canceled
}
c.err = err
d, _ := c.done.Load().(chan struct{})
if d == nil {
c.done.Store(closedchan)
} else {
close(d)
}
for child := range c.children {
// NOTE: acquiring the child's lock while holding parent's lock.
child.cancel(false, err)
}
c.children = nil
c.mu.Unlock()
if removeFromParent {
removeChild(c.Context, c)
}
}
// closedchan is a reusable closed channel.
var closedchan = make(chan struct{})
- removeFromParent是一个bool值,标识当前的context是否需要从parent context的children map中删除,第二个err则是cancel后的错误
- 首先先检验传入的err是否为空,空则panic
- 加锁
- 如果当前的cancelCtx的err不为nil,则说明已经被cancel了,则解锁返回
- 把err传入当前的cancelCtx的err
- 处理当前的cancelCtx的done的channel,如果channel没有初始化,就直接存储一个closedChan,否则关闭该channel
- 遍历当前cancelCtx的所有子context,依次补刀终止,将children context都进行cancel
- 解锁
- 根据传入的removeFromParent判断是否需要手动的把当前cancelCtx从它的parent children map 中移除
接着看removeChild
// removeChild removes a context from its parent.
func removeChild(parent Context, child canceler) {
p, ok := parentCancelCtx(parent)
if !ok {
return
}
p.mu.Lock()
if p.children != nil {
delete(p.children, child)
}
p.mu.Unlock()
}
- 如果parent不是cancelCtx类型,直接返回
- 加锁
- 把child从parent的children中删除
- 解锁
4 第三个实现类 timerCtx
4.1 数据结构
// A timerCtx carries a timer and a deadline. It embeds a cancelCtx to
// implement Done and Err. It implements cancel by stopping its timer then
// delegating to cancelCtx.cancel.
type timerCtx struct {
cancelCtx
timer *time.Timer // Under cancelCtx.mu.
deadline time.Time
}
timerCtx在cancelCtx基础上又做了一层封装,除了继承cancelCtx的能力之外,新增了timer用于定时终止context,而且还增加了deadline字段用于记录timerCtx的过期时间。
4.2 timerCtx.Deadline()
func (c *timerCtx) Deadline() (deadline time.Time, ok bool) {
return c.deadline, true
}
context.Context 接口的Deadline api只在timerCtx中有效,用于展示context的过期时间。
4.3 timerCtx.cancel()
func (c *timerCtx) cancel(removeFromParent bool, err error) {
c.cancelCtx.cancel(false, err)
if removeFromParent {
// Remove this timerCtx from its parent cancelCtx's children.
removeChild(c.cancelCtx.Context, c)
}
c.mu.Lock()
if c.timer != nil {
c.timer.Stop()
c.timer = nil
}
c.mu.Unlock()
}
- 复用继承的cancelCtx的cancel函数,进行cancel处理
- 判断是否需要手动的从parent的children中移除,是就进行处理
- 加锁
- 停止timer.Timer,方便资源回收
- 解锁返回
4.4 context.WithTimeout 和 context.WithDeadline()
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
return WithDeadline(parent, time.Now().Add(timeout))
}
context.WithTImeout方法本质上是传入一段时间然后调用context.WithDeadline方法构造一个timerCtx
// Canceling this context releases resources associated with it, so code should
// call cancel as soon as the operations running in this Context complete.
func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) {
if parent == nil {
panic("cannot create context from nil parent")
}
if cur, ok := parent.Deadline(); ok && cur.Before(d) {
// The current deadline is already sooner than the new one.
return WithCancel(parent)
}
c := &timerCtx{
cancelCtx: newCancelCtx(parent),
deadline: d,
}
propagateCancel(parent, c)
dur := time.Until(d)
if dur <= 0 {
c.cancel(true, DeadlineExceeded) // deadline has already passed
return c, func() { c.cancel(false, Canceled) }
}
c.mu.Lock()
defer c.mu.Unlock()
if c.err == nil {
c.timer = time.AfterFunc(dur, func() {
c.cancel(true, DeadlineExceeded)
})
}
return c, func() { c.cancel(true, Canceled) }
}
context.WithDeadline方法传入的是一个具体的过期时间
- 检测parent非空
- 校验parent的过期时间是否早于自己,如果是的话说明设置的时间无效,直接构造一个cancelCtx返回
- 构建一个新的timerCtx
- 同步parent的cancel事件到子context
- 判断是否到了过期时间,如果到了,直接cancel timerCtx,并返回DeadlineExceeded错误
- 加锁
- 调用time.AfterFunc方法设置一个延时时间,到达时间时会终止该timeCtx,然后返回DeadlineExceeded错误
- 解锁
- 返回timeCtx,还有一个封装了cancel洛基的闭包cancel函数
5 第四个实现类 valueCtx
5.1 数据结构
// A valueCtx carries a key-value pair. It implements Value for that key and
// delegates all other calls to the embedded Context.
type valueCtx struct {
Context
key, val any
}
valueCtx跟cancelCtx一样继承了context.Context接口,并且一个valueCtx只有一组kv对
5.2 valueCtx.Value()
func (c *valueCtx) Value(key any) any {
if c.key == key {
return c.val
}
return value(c.Context, key)
}
- 如果当前传入的key跟当前valueCtx的key相等直接返回valueCtx存放的value
- 如果不相等,接着往valueCtx的parent context依次向上找
func value(c Context, key any) any {
for {
switch ctx := c.(type) {
case *valueCtx:
if key == ctx.key {
return ctx.val
}
c = ctx.Context
case *cancelCtx:
if key == &cancelCtxKey {
return c
}
c = ctx.Context
case *timerCtx:
if key == &cancelCtxKey {
return &ctx.cancelCtx
}
c = ctx.Context
case *emptyCtx:
return nil
default:
return c.Value(key)
}
}
}
- 用for循环由上到下,先判断context的类型,然后匹配key
- 如果时valueCtx类型,匹配的相等的key,直接返回,否则重置c的值为parent context,接着匹配key
- 如果时cancelCtx和timerCtx就是判断是否时cancelCtx类型,是就返回,否则重置c的值为parent context,接着匹配key
- emptyCtx直接返回nil
5.3 context.WithValue()
func WithValue(parent Context, key, val any) Context {
if parent == nil {
panic("cannot create context from nil parent")
}
if key == nil {
panic("nil key")
}
if !reflectlite.TypeOf(key).Comparable() {
panic("key is not comparable")
}
return &valueCtx{parent, key, val}
}
- 如果parent context为空,直接panic
- 如果key为空,panic
- 如果key的类型不可比较,panic
- 构建一个新的valueCtx对象返回
个人看法,context.WithValue()方法在并发场景下,是不会有读写问题,因为它每次写都是构建一个新的valueCtx对象,存放和读取某个kv对跟你从哪一个context开始查找有关,不太适合作为存储介质,太浪费空间