一、介绍
咱们在命令行 输出 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 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 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()调用。