Go-context底层原理(2)

39 阅读4分钟

cancelCtx.cancel

  • cancelCtx.cancel 方法有两个入参,第一个 removeFromParent 是一个 bool 值,表示当前 context 是否需要从父 context 的 children set 中删除;第二个 err 则是 cancel 后需要展示的错误;
//bool==当前 context 是否需要从父 context 的 children set 中删除
//err 是 cancel 后需要展示的错误
func (c *cancelCtx) cancel(removeFromParent bool, err error) {
//校验 cancelCtx 自带的 err 是否已经非空,若非空说明已被 cancel,则解锁返回;
//表示 如果要关掉这个ctx则必须产生一个err
    if err == nil {
        panic("context: internal error: missing cancel error")
    }
//加锁,涉及到并发,很多携程可能同时再操作这一个ctx节点
    c.mu.Lock()
//校验 cancelCtx 自带的 err 是否已经非空,若非空说明已被关掉,则解锁返回;    
    if c.err != nil {
        c.mu.Unlock()
        return // already canceled
    }
//将传入的 err 赋给 cancelCtx.err
    c.err = err
    
//处理 cancelCtx 的 channel,若 channel 此前未初始化,则直接注入一个 closedChan,否则关闭该 channel
    d, _ := c.done.Load().(chan struct{})
    if d == nil {
        c.done.Store(closedchan)
    } else {
        close(d)
    }
//关掉下游的子ctx
    for child := range c.children {
        // NOTE: acquiring the child's lock while holding parent's lock.
        child.cancel(false, err)
    }
//因为将下游的子ctx都关闭了 将他设置到nil  方便gc回收
    c.children = nil
    c.mu.Unlock()
//如果需要在父ctx中删除此ctx节点则删除
    if removeFromParent {
        removeChild(c.Context, c)
    }
}

走进removeChild 方法中,观察如何将 cancelCtx 从父ctx的 children set 中移除:

func removeChild(parent Context, child canceler) {
//如果 parent 不是 cancelCtx,直接返回(因为只有 cancelCtx 才有 children set)
    p, ok := parentCancelCtx(parent)
    if !ok {
        return
    }
    p.mu.Lock()
    if p.children != nil {
//从 parent 的 children set 中删除对应 child
        delete(p.children, child)
    }
    p.mu.Unlock()
}

timerCtx

首先看一下timerCtx的数据结构

type timerCtx struct {
    cancelCtx
    timer *time.Timer // Under cancelCtx.mu.

    deadline time.Time
}

timerCtx 在 cancelCtx 基础上又做了一层封装,除了继承 cancelCtx 的能力之外,新增了一个 time.Timer 用于定时终止 context;另外新增了一个 deadline 字段用于字段 timerCtx 的过期时间.

timerCtx.Deadline()

context.Context interface 下的 Deadline api 仅在 timerCtx 中有效,用于展示其过期时间.

func (c *timerCtx) Deadline() (deadline time.Time, ok bool) {
    return c.deadline, true
}

timerCtx.cancel

用于关闭ctx的方法。

  • 复用继承的 cancelCtx 的 cancel 能力,进行 cancel 处理;
  • 判断是否需要手动从父ctx的 children set 中移除,若是则进行处理
  • 停止 time.Timer
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()
}

context.WithTimeout & context.WithDeadline

context.WithTimeout 方法用于构造一个 timerCtx,本质上会调用 context.WithDeadline 方法:

func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
    return WithDeadline(parent, time.Now().Add(timeout))
}
  •  校验 父ctx 非空;
  •  校验 parent 的过期时间是否早于自己,若是,则构造一个 cancelCtx 返回即可;
  •  构造出一个新的 timerCtx;
  •  启动守护方法,同步 parent 的 cancel 事件到子 context;
  •  判断过期时间是否已到,若是,直接 cancel timerCtx,并返回 DeadlineExceeded 的错误;
  •  加锁;
  •  启动 time.Timer,设定一个延时时间,即达到过期时间后会终止该 timerCtx,并返回 DeadlineExceeded 的错误;
  •  解锁;
  •  返回 timerCtx,已经一个封装了 cancel 逻辑的闭包 cancel 函数.
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) }
}

valueCtx

  • • valueCtx 同样继承了一个 parent context;
  • • 一个 valueCtx 中仅有一组 kv 对.
type valueCtx struct {
    Context
    key, val any
}

valueCtx.Value()

  • • 假如当前 valueCtx 的 key 等于用户传入的 key,则直接返回其 value;
  • • 假如不等,则从 parent context 中依次向上寻找.
func (c *valueCtx) Value(key any) any {
    if c.key == key {
        return c.val
    }
    return value(c.Context, key)
}
  • • 启动一个 for 循环,由下而上,由子及父,依次对 key 进行匹配;
  • • 其中 cancelCtx、timerCtx、emptyCtx 类型会有特殊的处理方式;
  • • 找到匹配的 key,则将该组 value 进行返回.
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)
        }
    }
}

valueCtx 用法小结

阅读源码可以看出,valueCtx 不适合视为存储介质,存放大量的 kv 数据,原因有三:

  • • 一个 valueCtx 实例只能存一个 kv 对,因此 n 个 kv 对会嵌套 n 个 valueCtx,造成空间浪费;
  • • 基于 k 寻找 v 的过程是线性的,时间复杂度 O(N);
  • • 不支持基于 k 的去重,相同 k 可能重复存在,并基于起点的不同,返回不同的 v. 由此得知,valueContext 的定位类似于请求头,只适合存放少量作用域较大的全局 meta 数据.

context.WithValue()

  • • 倘若 parent context 为空,panic;
  • • 倘若 key 为空 panic;
  • • 倘若 key 的类型不可比较,panic;
  • • 包括 parent context 以及 kv对,返回一个新的 valueCtx.
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}
}