这也是go语言的并发工具,用来一对多管理goroutine,它可以跟踪goroutine并控制
部分代码以及思路参考:Go语言实战笔记(二十)| Go Context | 飞雪无情的博客 (flysnow.org)
context控制goroutine实例代码:
func main() {
ctx, cancel := context.WithCancel(context.Background())
go func(ctx context.Context) {
for {
select {
case <-ctx.Done():
fmt.Println("监控退出,停止了...")
return
default:
fmt.Println("goroutine监控中...")
time.Sleep(2 * time.Second)
}
}
}(ctx)
time.Sleep(10 * time.Second)
fmt.Println("可以了,通知监控停止")
cancel()
//为了检测监控过是否停止,如果没有监控输出,就表示停止了
time.Sleep(5 * time.Second)
}
代码实现了用select+context结束一个goroutine
1:context.Background()返回context树的根节点,它不可被撤销,主要作用是为了延申子节点
2:我们把根节点当作参数传入context.WithCancel(parent)后就可以得到一个可撤销的子节点,把他作为跟踪goroutine的主要参数
3:如果在goroutine中接收到<-ctx.Done()的值证明这个goroutine该结束了
4:当我们调用撤销函数时,context就会接收到信号,Done方法通道关闭来对goroutine进行控制
Done方法是一个struct{}类型的一个通道,当前context值被撤销时,通道会立即关闭
控制多个goroutine我们可以用一个context值进行追踪,达到条件时撤销,以达到监控控制goroutine的目的
func main() {
ctx, cancel := context.WithCancel(context.Background())
go watch(ctx,"【监控1】")
go watch(ctx,"【监控2】")
go watch(ctx,"【监控3】")
time.Sleep(10 * time.Second)
fmt.Println("可以了,通知监控停止")
cancel()
//为了检测监控过是否停止,如果没有监控输出,就表示停止了
time.Sleep(5 * time.Second)
}
func watch(ctx context.Context, name string) {
for {
select {
case <-ctx.Done():
fmt.Println(name,"监控退出,停止了...")
return
default:
fmt.Println(name,"goroutine监控中...")
time.Sleep(2 * time.Second)
}
}
}
context底层结构
type Context interface {
// Done returns a channel that is closed when this Context is canceled
// or times out.
Done() <-chan struct{}
// Err indicates why this context was canceled, after the Done channel
// is closed.
Err() error
// Deadline returns the time when this Context will be canceled, if any.
Deadline() (deadline time.Time, ok bool)
// Value returns the value associated with key or nil if none.
Value(key interface{}) interface{}
}
我们可以看到包含了4个方法
Done 方法在Context被取消或超时时返回一个close的channel,close的channel可以作为广播通知,告诉给context相关的函数要停止当前工作然后返回。
Err方法返回context取消的原因,为什么被取消。
Deadline返回context何时会超时。
Value返回context相关的值。是一个键值对
go内置也帮我们实现了两个接口
var (
background = new(emptyCtx)
todo = new(emptyCtx)
)
func Background() Context {
return background
}
func TODO() Context {
return todo
}
Background,主要用于main函数、初始化以及测试代码中,作为Context这个树结构的最顶层的Context,也就是根Context。
Todo返回空的上下文(表明应用的不确定性)
他们的本质都是不可撤销的,底层结构:
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
}
context继承
func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc)
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
func WithValue(parent Context, key, val interface{}) Context
WithCancel:返回一个子Context和一个cancel函数用来撤销
WithDeadLine:定义时间,超时自动关闭
WithTimeout: 等价于 WithDeadline(parent, time.Now().Add(timeout)).
WithValue:生成一个绑定了一个键值对数据的Context,这个绑定的数据可以通过
Context.Value
方法访问到
WithValue传递元数据
var key string="name"
func main() {
ctx, cancel := context.WithCancel(context.Background())
//附加值
valueCtx:=context.WithValue(ctx,key,"【监控1】")
go watch(valueCtx)
time.Sleep(10 * time.Second)
fmt.Println("可以了,通知监控停止")
cancel()
//为了检测监控过是否停止,如果没有监控输出,就表示停止了
time.Sleep(5 * time.Second)
}
func watch(ctx context.Context) {
for {
select {
case <-ctx.Done():
//取出值
fmt.Println(ctx.Value(key),"监控退出,停止了...")
return
default:
//取出值
fmt.Println(ctx.Value(key),"goroutine监控中...")
time.Sleep(2 * time.Second)
}
}
}
我们可以实现用context键值对方式来传递数据,不必须的值最好不要用value来传递
通常 Context 都是做为函数的第一个参数进行传递(规范性做法),并且变量名建议统一叫 ctx
Context 是线程安全的,可以放心地在多个 goroutine 中使用。
当你把 Context 传递给多个 goroutine 使用时,只要执行一次 cancel 操作,所有的 goroutine 就可以收到 取消的信号
不要把原本可以由函数参数来传递的变量,交给 Context 的 Value 来传递。
当一个函数需要接收一个 Context 时,但是此时你还不知道要传递什么 Context 时,可以先用 context.TODO 来代替,而不要选择传递一个 nil。
当一个 Context 被 cancel 时,继承自该 Context 的所有 子 Context 都会被 cancel