Go 组件 Context 源码学习笔记

2023-02-23 0 648

译者:jasonjguo,百度 CSIG 前台合作开发技师

前段时间职能部门转 go 有一两年了,在网路上始终看见自己所推荐学 go 能自学下里头的 context 源代码,言简意赅。看了下的确略有斩获。责任编辑是如前所述我前段时间对 context 源代码自学的许多心得体会累积,望我们通达股份。

为何要采用 Context?

Go 强悍而简约的mammalian潜能

井鼠 go 最称道的机能要数 go 强悍而简约的mammalian潜能。

func main(){ go func(){ fmt.Println(“Hello World”) }() }

透过单纯的 go func(){},go 能加速聚合捷伊PulseAudio并运转。

想像两个没 context 的当今世界

有mammalian的地方性就有武林。每一C语言都有各别的mammalian程式设计形式,也有相同的mammalian掌控形式,比如说 java 透过 join()来做仇敌缓存并行。go 里头常见于PulseAudio协同工作和管理工作的有 channel 和 sync 包。比如说 channel 能通告PulseAudio做某一操作形式(选择退出,堵塞等),sync 能上锁和并行。

倘若我要与此同时实现两个能与此同时停用大部份PulseAudio的流程,能这种与此同时实现:

closed := make(chan struct{}) for i := 0; i < 2; i++ { // do something go func(i int) { select { case <-closed: fmt.Printf(“%d Closed\n”, i) } }(i) } // 发送指令停用大部份PulseAudio close(closed) time.Sleep(1 * time.Second)

因为 go 的PulseAudio不支持直接从外部选择退出,不像 C++和 Java 有个缓存 ID 能操作形式。所以只能透过PulseAudio自己选择退出的形式。一般来说透过 channel 来掌控是最方便的。

如果我想加点机能,比如说到时间后选择退出,只要给 channel 增加停用条件即可:

closed := make(chan struct{}) for i := 0; i < 2; i++ { go func(i int) { // do something select { case <-closed: fmt.Printf(“%d Timeout\n”, i) } }(i) } // 加个时间条件 ta := time.After(5* time.Second)select { case <-ta: close(closed) } time.Sleep(1 * time.Second)

用 Context 精简代码

上面的代码已经够单纯了,但是还是显得有些复杂。比如说每次都要在PulseAudio内部增加对 channel 的判断,也要在外部设置停用条件。试想一下,如果流程要限制的是总时长,而不是单个操作形式的时长,这种每一操作形式要限制多少时间也是个难题。

Go 组件 Context 源码学习笔记

这个时候就轮到 Context 登场了。Context 顾名思义是PulseAudio的上下文,主要用于跟踪PulseAudio的状态,能做许多单纯的PulseAudio掌控,也能记录许多PulseAudio信息。

下面试着用 Context 改造下前面的例子。

// 空的父context pctx := context.TODO() // 子context(携带有超时信息),cancel函数(能主动触发取消) //ctx, cancel := context.WithTimeout(pctx, 5*time.Second) ctx, _ := context.WithTimeout(pctx, 5*time.Second) for i := 0; i < 2; i++ {go func(i int) { // do something // 大部分工具库内置了对ctx的判断,下面的部分几乎能省略 select { case<-ctx.Done(): fmt.Printf(“%d Done\n”, i) } }(i) } // 调用cancel会直接停用ctx.Done()返回的管道,不用等到超时 //cancel() time.Sleep(6* time.Second)

透过 Context 能进一步简化掌控代码,且更为友好的是,大多数 go 库,如 http、各种 db driver、grpc 等都内置了对 ctx.Done()的判断,我们只需要将 ctx 传入即可。

Context 基础用法

接下来介绍 Context 的基础用法,最为重要的就是 3 个基础潜能,取消、超时、附加值

新建两个 Context

ctx := context.TODO() ctx := context.Background()

这两个形式返回的内容是一样的,都是返回两个空的 Context,这个 Context 一般用来做父 Context。

WithCancel

// 函数声明 func WithCancel(parent Context) (ctx Context, cancel CancelFunc) // 用法:返回两个子Context和主动取消函数ctx, cancel := context.WithCancel(parentCtx)

这个函数相当重要,会根据传入的 Context 聚合两个子 Context 和两个取消函数。当父 Context 有相关取消操作形式,或者直接调用 cancel 函数的话,子 Context 就会被取消。

举个日常业务中常见的例子:

// 一般操作形式比较耗时或者涉及远程调用等,都会在输入参数里带上两个ctx,这也是公司代码规范里提倡的 func Do(ctx context.Context, …) { ctx, cancel := context.WithCancel(parentCtx) // 与此同时实现某些业务逻辑 // 当遇到某种条件,比如说流程出错,就取消掉子Context,这种子Context绑定的PulseAudio也能跟着选择退出 if err != nil { cancel() } }

WithTimeout

// 函数声明 func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) // 用法:返回两个子Context(会在一两年后自动取消),主动取消函数 ctx := context.WithTimeout(parentCtx, 5*time.Second)

这个函数在日常工作中采用得非常多,单纯来说就是给 Context 附加两个超时掌控,当超时 ctx.Done()返回的 channel 就能读取到值,PulseAudio能透过这个形式来判断执行时间是否满足要求。

举个日常业务中常见的例子:

// 一般操作形式比较耗时或者涉及远程调用等,都会在输入参数里带上两个ctx,这也是公司代码规范里提倡的 func Do(ctx context.Context, …){ ctx, cancel := context.WithTimeout(parentCtx)// 与此同时实现某些业务逻辑 for { select { // 轮询检测是否已经超时 case <-ctx.Done(): return // 有时也会附加许多错误判断 case<-errCh: cancel()default: } } }

现在大部分 go 库都与此同时实现了超时判断逻辑,我们只需要传入 ctx 就好。

WithDeadline

// 函数声明 func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) // 用法:返回两个子Context(会在指定的时间自动取消),主动取消函数 ctx, cancel := context.WithDeadline(parentCtx, time.Now().Add(5*time.Second))

这个函数感觉用得比较少,和 WithTimeout 相比的话就是采用的是截止时间。

WithValue

// 函数声明 func WithValue(parent Context, key, val interface{}) Context // 用法: 传入父Context和(key, value),相当于存两个kv ctx := context.WithValue(parentCtx, “name”, 123) // 用法:将key对应的值取出v := ctx.Value(“name”)

因为这个形式实在是太常见了,比如说 grpc-go 里的 metadata 就使用这个形式将结构体存储在 ctx 里。

func NewOutgoingContext(ctx context.Context, md MD) context.Context { returncontext.WithValue(ctx, mdOutgoingKey{}, rawMD{md: md}) }

Context 源代码与此同时实现

理解 Context

Context 是两个接口

虽然我们平时写代码时直接 context.Context 拿来就用,但实际上 context.Context 是两个接口,源代码里是有多种相同的与此同时实现的,借此与此同时实现相同的机能。

type Context interface { // 返回这个ctx预期的结束时间 Deadline() (deadline time.Time, ok bool) // 返回两个channel,当执行结束或者取消时被close,我们平时能用这个来判断ctx绑定的协程是否该选择退出。与此同时实现里用的懒汉模式,所以一开始可能会返回nil Done() <-chan struct{} // 如果未完成,返回nil。已完成源代码里目前就两种错误,已被取消或者已超时Err() error// 返回ctx绑定的key对应的value值 Value(key interface{}) interface{} }

Context 们是一棵树

Go 组件 Context 源码学习笔记

context 整体是两个树形结构,相同的 ctx 间可能是兄弟节点或者是父子节点的关系。

与此同时由于 Context 接口有多种相同的与此同时实现,所以树的节点可能也是多种相同的 ctx 与此同时实现。总的来说我觉得 Context 的特点是:

树形结构,每次调用 WithCancel, WithValue, WithTimeout, WithDeadline 实际是为当前节点在追加子节点;继承性,某个节点被取消,其对应的子树也会全部被取消;多样性,节点存在相同的与此同时实现,故每一节点会附带相同的机能。

Context 的果子们

在源代码里实际只有 4 种与此同时实现,要弄懂 context 的源代码其实把这 4 种对应的与此同时实现自学一下就行,他们分别是:

emptyCtx:两个空的 ctx,一般用于做根节点;cancelCtx:核心,用来处理取消相关的操作形式;timerCtx:用来处理超时相关操作形式;valueCtx:附加值的与此同时实现形式。

现在先单纯对这几个与此同时实现有个概念,后面会对其中核心关键的部分讲解下。

Context 类图

Go 组件 Context 源码学习笔记

从类图中能看出,源代码里有 4 种结构和 3 种接口,相对于其他 go 库源代码来说是比较单纯的。

核心的接口是 Context,里头包含了最常见的判断是否处理完成的 Done()形式 。其他大部份结构都透过 ① 与此同时实现形式或 ② 组合的形式来与此同时实现该接口。

核心的结构是 cancelCtx,被 timerCtx 包含。cancelCtx 和 timerCtx 能说代表了 Context 库最核心的取消和超时相关的与此同时实现,也最为复杂些。

Context 源代码

因为篇幅关系,不会把每一行源代码都拎出来,会挑比较重点的形式讲下。由于平时我们采用都是透过几个固定的形式入口,所以会围绕这几个形式讲下。

emptyCtx

对外体现

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

TODO(),Background()其实都是返回两个 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 } func (e *emptyCtx) String() string { switch e { case background: return “context.Background” case todo: return “context.TODO” } return “unknown empty Context” }

这个结构非常单纯,都是返回 nil。emptyCtx 主要用于新建两个独立的树。比方说,我想在PulseAudio里做些异步操作形式,但是又想脱离主PulseAudio的 ctx 掌控如采用独立的超时限制,就能采用这种形式。但是在整个 go 流程里只有 todo 和 background 两个大根节点,所以TODO()Background()其实是新建第二层级的子树。

func demo(ctx context.Context){ nctx := context.TODO() nctx := context.WithTimeout(nctx, 5*time.Second) … }
Go 组件 Context 源码学习笔记

valueCtx

对外体现

// 设置key, value值 func WithValue(parent Context, key, valinterface{}) Context { if key == nil { panic(“nil key”) } if!reflectlite.TypeOf(key).Comparable() {panic(“key is not comparable”) } // 在当前节点下聚合捷伊子节点 return &valueCtx{parent, key, val} } // 根据key读取value func (c *valueCtx) Value(key interface{}) interface{} { if c.key == key { return c.val } return c.Context.Value(key) }

与此同时实现

type valueCtx struct { Context key,val interface{} } // 根据key读取value func (c *valueCtx) Value(key interface{})interface{} { // 每一ctx只绑定两个key,匹配则返回。否则向上追溯到匹配为止 if c.key == key { return c.val } returnc.Context.Value(key) }

从与此同时实现上能看出,每当我们往 ctx 里调 WithValue 塞值时,都会聚合两个捷伊子节点。调用的次数多了,聚合的子树就很庞大。

Go 组件 Context 源码学习笔记

若当前节点的 key 和传入的 key 不匹配会沿着继承关系向上递归查找。递归到根就变成 nil,表示当前 key 在该子树序列里没存。

cancelCtx

介绍完上面两种比较单纯的结构后,终于要来到复杂的 cancelCtx。cancelCtx 和 timerCtx 关联性很强,基本上弄懂两个,另外两个也差不多了。

对外形式

func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { // 新建两个cancelCtx c := newCancelCtx(parent) // 将父节点的取消函数和子节点关联,做到父节点取消,子节点也跟着取消 propagateCancel(parent, &c)// 返回当前节点和主动取消函数(调用会将自身从父节点移除,并返回两个已取消错误) return &c, func() { c.cancel(true, Canceled) } }

对外的形式里包含的几个方法都是重点的形式,后面主要讲下

结构

type cancelCtx struct { Context mu sync.Mutex // protects following fieldsdone chanstruct{} // 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 } done:用于判断是否完成cancel:存子取消节点err:取消时的错误,超时或主动取消type canceler interface { cancel(removeFromParent bool, err error) Done() <-chan struct{} }

这个接口约定了能取消的 context,比如说 cancelCtx 和 timerCtx 是能取消的,emptyCtx 和 valueCtx 是不能取消的。

初始化

// newCancelCtx returns an initialized cancelCtx. func newCancelCtx(parent Context) cancelCtx { returncancelCtx{Context: parent} }

初始化就是将父节点设置了一下,其他不设置。

cancelCtx 的取消与此同时实现

// cancel closes c.done, cancels each of cs children, and, if // removeFromParent is true, removes c from its parents children. func (c*cancelCtx) cancel(removeFromParent bool, err error) { // 取消无论是透过父节点还是自身主动取消,err都不为空 if err == nil{ panic(“context: internal error: missing cancel error”) } c.mu.Lock() if c.err != nil { // c.err 不为空表示已经被取消过,比如说父节点取消时子节点可能已经主动调用过取消函数 c.mu.Unlock() return // already canceled } c.err = err if c.done == nil { // closedchan 是两个已经停用的channel,要特殊处理是因为c.done是懒加载的形式。只有调用c.Done()时才会实际创建 c.done = closedchan } else{ close(c.done) } // 递归取消子节点 for child := range c.children { // NOTE:acquiring the childs lock while holding parents lock. child.cancel(false, err) } c.children = nil c.mu.Unlock() // 从父节点中移除当前节点 ifremoveFromParent { removeChild(c.Context, c) } }

整个过程能总结为

前置判断,看是否为异常情况停用 c.done,这种外部调用 cancelCtx.Done()就会有返回结果递归调用子节点的 cancel 形式视情况从父节点中移除子节点

这里child.cancel(false, err)不从父节点移除子节点是因为当前节点操作形式已取过锁,移除操作形式会再取锁造成冲突,故先全部 cancel 后再将 children 置为 nil 一次性移除。

propagateCancel 绑定父子节点的取消关系

// propagateCancel arranges for child to be canceled when parent is. func propagateCancel(parent Context, child canceler){ done := parent.Done()if done == nil { // 若当前节点追溯到根没cancelCtx或者timerCtx的话,表示当前节点的祖先没能取消的结构,后面的父子绑定的操作形式就能不用做了,可参考下图 return // parent is never canceled } select { case <-done: // 父节点已取消就直接取消子节点,无需移除是因为父子关系还没加到parent.children // 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 { // 绑定父子关系 ifp.children ==nil { p.children = make(map[canceler]struct{}) } p.children[child] = struct{}{} } p.mu.Unlock() }else { // 当ctx是合作开发者自定义的并继承context.Context接口会进入这个分支,另起两个PulseAudio来监听取消动作,因为合作开发者自定义的习惯可能和源代码中用c.done和c.err的判断形式略有相同 atomic.AddInt32(&goroutines, +1) go func() { select { case<-parent.Done(): child.cancel(false, parent.Err()) case <-child.Done(): } }() } }
Go 组件 Context 源码学习笔记

① 当祖先继承链里没 cancelCtx 或 timerCtx 等与此同时实现时,Done()形式总是返回 nil,能作为前置判断

② parentCancelCtx 取的是能取消的前段时间祖先节点

总结

总结一下,cancelCtx 的作用其实就两个:

绑定父子节点,并行取消信号,父节点取消子节点也跟着取消提供主动取消函数

timerCtx

结构体

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

相比 cancelCtx 多了两个计时器和截止时间

取消形式

func (c *timerCtx)cancel(removeFromParent bool, err error) {c.cancelCtx.cancel(false, err) if removeFromParent { // Remove this timerCtx from its parent cancelCtxs children. removeChild(c.cancelCtx.Context, c) } c.mu.Lock() if c.timer != nil { c.timer.Stop() c.timer = nil } c.mu.Unlock() }

取消形式就是直接调用 cancelCtx 的取消外加计时器停止

对外形式

func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) { if cur, ok := parent.Deadline(); ok && cur.Before(d) {// 传入的截止时间在父节点截止时间之后,则父节点取消时会并行取消当前子节点,不需要额外再设置计费器了,能当普通的cancelCtx对待。 // 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 的主要机能就是用于掌控PulseAudio选择退出附加链路信息。核心与此同时实现的结构体有 4 个,最复杂的是 cancelCtx,最常见的是 cancelCtx 和 valueCtx。整体呈树状结构,父子节点间并行取消信号。

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务