Golang Context的常规操作
context
context是go的并发编程的常用模式,可以通过context来处理超时,取消任务等一系列操作
用context 取消任务
示例
func main() {
parentCtx, cancel := context.WithCancel(context.Background())
for i := 0; i < 10; i++ {//启动10个goroutine
childCtx, _ := context.WithCancel(parentCtx)//创建子的context
go func(ctx context.Context, index int) {
for {
select {
case <-ctx.Done():
fmt.Println("goroutine done:", index)
return
}
}
}(childCtx, i)
}
<-time.After(time.Second * 2)//2秒后开始关闭
cancel()//关掉paraentContext,会引发所有子的context被关闭
time.Sleep(time.Second)//sleep 1秒为了能观察10个goroutine的推出情况
return
}
输出结果
goroutine done: 2
goroutine done: 4
goroutine done: 3
goroutine done: 8
goroutine done: 1
goroutine done: 7
goroutine done: 6
goroutine done: 9
goroutine done: 0
goroutine done: 5
超时任务处理
未完待续…