Context(即上下文)是常用的并发控制技术,可以控制一组多级的goroutine。
Context 仅仅是一个接口定义,跟据实现的不同,可以衍生出不同的context类型。
上下文有下面四种类型
1、WithCancel
1 2 3 4 5 6
| func main() { ctx, cancel := context.WithCancel(context.Background()) go HandelRequest(ctx) time.Sleep(1 * time.Second) cancel() }
|
2、WithDeadline
1 2 3 4 5 6 7 8 9 10
| func main() { now := time.Now() ctx, cancel := context.WithDeadline(context.Background(), now.Add(3*time.Second)) go HandelRequest(ctx) time.Sleep(3 * time.Second) cancel() }
|
3、WithTimeout
1 2 3 4 5 6
| func main() { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) go HandelRequest(ctx) time.Sleep(10 * time.Second) cancel() }
|
4、WithValue
作用是可以传递参数给到其他goroutine
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| func main() { ctx := context.WithValue(context.Background(), "id", "1") go HandelRequest(ctx) time.Sleep(10 * time.Second) }
func HandelRequest(ctx context.Context) { for { select { case <-ctx.Done(): fmt.Println("HandelRequest Done.") return default: fmt.Println("HandelRequest running, parameter: ", ctx.Value("parameter")) time.Sleep(2 * time.Second) } } }
|