关于go:go源码阅读-context

3次阅读

共计 1138 个字符,预计需要花费 3 分钟才能阅读完成。

一、介绍

咱们在命令行 输出 go doc context 能够看到多 context 包的介绍。
context 高低问,是连贯不同的 goroutine,让每个协程能够有父子关系,并且领有本人的独特的值
WithValue(), 或者解决超时 WithTimeout(),定时 WithDeadline(),勾销协程 WithCancel() 操作。
在 go 官网博客 https://go.dev/blog/context 也有想起的介绍。

源码地址 src/context/context.go
在 context 包里,共有 4 种类型的上下文

上下文 如何获取 作用
emptyCtx Background()或 TODO() 初始化 父级 上下文
valueCtx WithValue() 初始化一个带 key,value子级 上下文
cancelCtx WithCancel() 初始化一个 能够勾销 子级 上下文
timerCtx WithDeadline()或 WithTimeout() 初始化一个带有 定时 以及 能够勾销 子级 上下文

从协程的角度来看如下图:

从上下文的角度来看如下图:

二、emptyCtx 初始化默认父级上下文
源码如下:

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

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

type Context interface {Deadline() (deadline time.Time, ok bool)
    Done() <-chan struct{}
    Err() error
    Value(key interface{}) interface{}}

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

emptyCtx 是是一个实现了 Context 接口的 上下文。
没有做什么逻辑,只是为了实现一个变量,可能让 Background()和 TODO()调用。

正文完
 0