context在Golang的1.7版本之前,是在包golang.org/x/net/context中的,但是后来发现其在很多地方都是需要用到的,所有在1.7开始被列入了Golang的标准库。Context包专门用来简化处理单个请求的多个goroutine之间与请求域的数据、取消信号、截止时间等相关操作,那么这篇文章就来看看其用法和实现原理。
源码分析
首先我们来看一下Context里面核心的几个数据结构:
Context interface
type Context interface {
Deadline() (deadline time.Time, ok bool)
Done() <-chan struct{}
Err() error
Value(key interface{}) interface{}
}
Deadline返回一个time.Time,是当前Context的应该结束的时间,ok表示是否有deadline。
Done方法在Context被取消或超时时返回一个close的channel,close的channel可以作为广播通知,告诉给context相关的函数要停止当前工作然后返回。
Err方法返回context为什么被取消。
Value可以让Goroutine共享一些数据,当然获得数据是协程安全的。但使用这些数据的时候要注意同步,比如返回了一个map,而这个map的读写则要加锁。
canceler interface
canceler interface定义了提供cancel函数的context:
type canceler interface {
cancel(removeFromParent bool, err error)
Done() <-chan struct{}
}
其现成的实现有4个:
-
emptyCtx:空的Context,只实现了Context interface;
cancelCtx:继承自Context并实现了cancelerinterface
timerCtx:继承自cancelCtx,可以用来设置timeout;
valueCtx:可以储存一对键值对;
继承Context
context包提供了一些函数,协助用户从现有的 Context 对象创建新的 Context 对象。这些Context对象形成一棵树:当一个 Context对象被取消时,继承自它的所有Context都会被取消。
Background是所有Context对象树的根,它不能被取消,它是一个emptyCtx的实例:
var (
background = new(emptyCtx)
)
func Background() Context {
return background
}
生成Context的主要方法
WithCancel
func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
c := newCancelCtx(parent)
propagateCancel(parent, &c)
return &c, func() { c.cancel(true, Canceled) }
}
返回一个cancelCtx示例,并返回一个函数,可以在外层直接调用cancelCtx.cancel()来取消Context。
WithDeadline
func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) {
if cur, ok := parent.Deadline(); ok && cur.Before(deadline) {
return WithCancel(parent)
}
c := &timerCtx{
cancelCtx: newCancelCtx(parent),
deadline: deadline,
}
propagateCancel(parent, c)
d := time.Until(deadline)
if d <= 0 {
c.cancel(true, DeadlineExceeded) // deadline has already passed
return c, func() { c.cancel(true, Canceled) }
}
c.mu.Lock()
defer c.mu.Unlock()
if c.err == nil {
c.timer = time.AfterFunc(d, func() {
c.cancel(true, DeadlineExceeded)
})
}
return c, func() { c.cancel(true, Canceled) }
}









