强烈建议读者先完成http://blog.golang.org/pipelines的阅读,此文对于go的channel的用法会让初学者有一种豁然开朗的感觉。
简介
context是一个在go中时常用到的程序包,google官方开发。特别常见的一个应用场景是由一个请求衍生出的各个goroutine之间需要满足一定的约束关系,以实现一些诸如有效期,中止routine树,传递请求全局变量之类的功能。使用context实现上下文功能约定需要在你的方法的传入参数的第一个传入一个context.Context类型的变量。我们将通过源代码的阅读和一些示例代码来说明context的用法。
文档在此:https://godoc.org/golang.org/x/net/context,另有一篇官方博客http://blog.golang.org/context
核心接口Context
type Context interface {
Deadline() (deadline time.Time, ok bool)
Done() <-chan struct{}
Err() error
Value(key interface{}) interface{}
}
默认错误:
var Canceled = errors.New("context canceled")
var DeadlineExceeded = errors.New("context deadline exceeded")
空Context:
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"
}
包中提供的两个空Context:
var (
background = new(emptyCtx)
todo = new(emptyCtx)
)
func Background() Context {
return background
}
func TODO() Context {
return todo
}
Cancel
cancelCtx结构体继承了Context,实现了canceler方法:
//*cancelCtx 和 *timerCtx 都实现了canceler接口,实现该接口的类型都可以被直接canceled
type canceler interface {
cancel(removeFromParent bool, err error)
Done() <-chan struct{}
}
type cancelCtx struct {