Context相关原理

151 阅读5分钟

context 主要作用

    context主要作用是在异步场景中实现并发协调 很多函数的第一个参数都是Context.context 以及对goroutine的生命周期控制 例如context.WithTimeOut context.WithDeadLine context.WithCancel 还可以进行数据的存储 context.WithValue

context 细节底层原理

type Context interface {
    Deadline() (deadline time.Time, ok bool)
    Done() <-chan struct{}
    Err() error
    Value(key any) any
}
    context就是一个接口类型 分析内容及名字可以知道 分别返回的是 过期时间/是否过期 、 <- chan struct{} (struct{}省内存 <-chan等待接收终止信号) 、 返回Context传递过程中的错误信息 一共有两种 var DeadlineExceeded error = deadlineExceededError{} 以及 var Canceled = errors.New("context canceled") 被取消了返回Canceled 超时返回DeadlineExceeded
 、 可以带值(context.WithValue)

我们常用的初始的Context要么是context.background() 要么是context.todo() 源码如下

var (
    background = new(emptyCtx)
    todo       = new(emptyCtx)
)
//emptyCtx如下
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 any) any {
    return nil
}
​
func (e *emptyCtx) String() string {
    switch e {
    case background:
        return "context.Background"
    case todo:
        return "context.TODO"
    }
    return "unknown empty Context"
}
​
/*
    这里有个关键的点就是实现的这个Done()方法 返回的 <-chan struct{}是个nil 那么意味着不管是写入还是读出这个chan 都会陷入阻塞状态
    其实background和todo没有区别 都是emptyCtx
*/

三个重要的Ctx: cancelCtx timerCtx 和 valueCtx

在并发场景下 如果你异步创建一个子协程/线程 但是并不知道它什么时候终止 那么你不应该去创建它 ->不能滥用并发 要有并发控制的概念。 context并不是横向扩展的 而一定是在父context的基础上进行继承扩展 它继承了父context的所有能力 同时我希望它具有新的能力 那么在此基础上新增;从而形成了一棵多叉树的形式 root节点就是上面提到的emptyCtx 。

多叉树形式下生命周期终止事件传递的单向性 ,当一个context需要终止的时候 那么这个终止事件会传递到它的所有子孙节点 让它们也同时终止。由于root节点是emptyCtx 没有终止的能力,如果想终止掉所有context 只能将root的所有子context都终止。context和协程是高度类似的,正好用来处理goroutine的生命周期;goroutine也形成的是多叉树而不是栈(串行)的数据结构 当一个goroutine创建多个子goroutine的时候 此时它们之间的关系是松耦合的 如果想要将子goroutine终止 那么正好引入context 将其全部终止。

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
}
​
type canceler interface {
    cancel(removeFromParent bool, err error)
    Done() <-chan struct{}
}
    cancelCtx中含有的Context就是它的父context, mu->并发锁, done 就是 chan struct{}使用atomic.Value也是为了原子性 可以断言成为chan struct{}, children 就是它的所有cancelCtx的子context 这里是为了生命周期终止事件的单项传递性 来保证改cancelContext终止之后 它的所有cancelCtx子context都终止。 
    canceler就是子cancelCtx 但是golang的编程哲学就是职责内聚 边界分明 父节点只需要关系子节点的cancel和Done 那就创建一个interface只暴露这两个特性 屏蔽其他性质 以防在调用的时候出现其他错误。
//其实cancelCtx并没有实现deadline方法 而是继承了父context的deadline能力 如果父context没有该能力的话 就是emptyCtx的Deadline//cancelCtX最重要的方法 WithCancel
func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
    if parent == nil {
        panic("cannot create context from nil parent")
    } 
    c := newCancelCtx(parent) //符合之前说的继承扩展 在parent的基础上加上cancel功能
    propagateCancel(parent, &c)
    return &c, func() { c.cancel(true, Canceled) }
}
​
//传递Cancel 保证它的cancelCtx子context都终止
func propagateCancel(parent Context, child canceler) {
    done := parent.Done()
    if done == nil {
        return // parent is never canceled 类似emptyCtx
    }
​
    select {
    case <-done:
        // parent is already canceled
        child.cancel(false, parent.Err())
        return
    default:
    }
​
    if p, ok := parentCancelCtx(parent); ok { //这里判断父context是否是cancelCtx类型 通过特殊协议以及断言
        p.mu.Lock()
        if p.err != nil {
            // parent has already been canceled
            child.cancel(false, p.err)  //父节点已经被取消了 那么终止其所有子cancelCtx
        } else {
            //如果还没被取消 就将该子context加入set
            if p.children == nil {
                p.children = make(map[canceler]struct{})
            }
            p.children[child] = struct{}{}
        }
        p.mu.Unlock()
    } else {
        //如果父节点不是cancelCtx 但是可能带有cancel能力 那么使用多路复用 监控parent 一旦取消就取消所有子cancelCtx
        //如果是chile就不需要有任何动作 这个传递是单向的
        atomic.AddInt32(&goroutines, +1)
        go func() {
            select {
            case <-parent.Done():
                child.cancel(false, parent.Err())
            case <-child.Done():
            }
        }()
    }
}
​
func parentCancelCtx(parent Context) (*cancelCtx, bool) {
    done := parent.Done()
    if done == closedchan || done == nil {
        return nil, false
    }
    p, ok := parent.Value(&cancelCtxKey).(*cancelCtx)  //如果是cancelCtx就返回自身 同时断言 这里断言成功就说明是cancelCtx
    /*
        func (c *cancelCtx) Value(key any) any {
            if key == &cancelCtxKey {
                return c
            }
            return value(c.Context, key)
         }
    */
    if !ok {
        return nil, false
    }
    pdone, _ := p.done.Load().(chan struct{})
    if pdone != done {
        return nil, false
    }
    return p, true
}
​
//核心方法 第一个参数是标志是否需要将其从父节点的set中取消
func (c *cancelCtx) cancel(removeFromParent bool, err error) {
    if err == nil { //父节点没有被cancel
        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{}) //atomic.value
    if d == nil {
        c.done.Store(closedchan)
    } else {
        close(d)
    }
    for child := range c.children {
        // 遍历所有child 将其终止
        child.cancel(false, err)
    }
    c.children = nil
    c.mu.Unlock()
​
    if removeFromParent {
        removeChild(c.Context, c)
    }
}
type timerCtx struct {
    cancelCtx
    timer *time.Timer // Under cancelCtx.mu.
​
    deadline time.Time
}
    这里可以看到 timerCtx也是具有cancel能力的 它的该能力继承于cancelCtx父节点 timer相当于一个定时器 当到达设定的时间时 将其终止, deadline就是截止时间了 很好理解 就是context interface中的DeadLine()返回的deadline
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()
}
​
//重写了cancelCtx的方法 当触发cancel方法后 它的定时器也没啥作用了 就将其终止 以免资源的浪费
​
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
    return WithDeadline(parent, time.Now().Add(timeout))
}
​
//这里可以看到 WithTimeOut和WithDeadline的区别就是相对时间和绝对时间 核心方法没有区别
​
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) //同cancelCtx
    dur := time.Until(d)
    //这里所有的错误类型都变成了 DeadlineExceeded 而不是Canceled 并不是主动取消 而是时间到了
   
    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) //定时器 在dur时间时 触发cancel
        })
    }
    return c, func() { c.cancel(true, Canceled) }
}
type valueCtx struct {
    Context
    key, val any
}
​
//有点像map 但是又不一样 不能作为大量存储k-v对的介质  下面介绍原因
func (c *valueCtx) Value(key any) any {
    if c.key == key {
        return c.val
    }
    return value(c.Context, key)
}
​
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)
        }
    }
}
//如果找不到的话 会循环查找父context 直到查找到或者到了emptyCtx为止 这里switch中对于cancelCtx和timerCtx的判断不用管 只是寻找父context可能会遇到的context类型 做一个特判
总结为什么valueCtx不适合作为大量存储k-v对的介质
1. 每次存储k-v对 都要嵌套创建一个valueCtx 造成空间的浪费
2. 时间复杂度 由于是一直向上寻找 相当于一个链表寻值的过程 时间复杂度是O(N) 不如map的O(1)
3. 不支持去重 每个嵌套创建的valueCtx可能key值相同 但是val不同 从不同的context进入 寻找key = k的val 取到的值可能不相同

以上内容都是我读小徐先生1212 up主的context详解的读书笔记 用来面试自测