funcworker1() { deep := 10 ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) //设定终止时间 defer cancel() go handle(ctx, 500*time.Millisecond, deep) select { case <-ctx.Done(): fmt.Println("main",ctx.Err()) } }
funchandle(ctx context.Context, duration time.Duration, deep int) { if deep > 0 { time.Sleep(200*time.Millisecond) go handle(ctx, duration, deep-1) } if ctx.value("token") != nil { fmt.Printf("token is %s\n", ctx.value("token")) } select { case <-ctx.Done(): fmt.Println("handle", ctx.Err()) case <-time.After(duration): fmt.Printf("process request with %v, %d\n", duration, deep) } }
场景二 操作终止
设置一个信号,信号出现则所有操作终止。
funcworker2() { deep := 10 ctx, cancel := context.WithCancel(context.Background()) //设定终止信号 go handle(ctx, 500*time.Millisecond, deep) time.Sleep(2*time.Second) //模拟一些操作 cancel() //发射终止信号 }
funchandle(ctx context.Context, duration time.Duration, deep int) { if deep > 0 { time.Sleep(200*time.Millisecond) go handle(ctx, duration, deep-1) } if ctx.value("token") != nil { fmt.Printf("token is %s\n", ctx.value("token")) } select { case <-ctx.Done(): fmt.Println("handle", ctx.Err()) case <-time.After(duration): fmt.Printf("process request with %v, %d\n", duration, deep) } }
场景三 跨协程异步共享数据
通过context传递一个数据给所有的子协程。
funcworker3() { deep := 10 ctx:= context.WithValue(context.Background(), "token", "val") //传递键值对 ctx,cancel:=context.WithTimeout(ctx, 2*time.Second) defer cancel() go handle(ctx, 500*time.Millisecond, deep) select { case <-ctx.Done(): fmt.Println("main", ctx.Err()) } }
funchandle(ctx context.Context, duration time.Duration, deep int) { if deep > 0 { time.Sleep(200*time.Millisecond) go handle(ctx, duration, deep-1) } if ctx.value("token") != nil { fmt.Printf("token is %s\n", ctx.value("token")) } select { case <-ctx.Done(): fmt.Println("handle", ctx.Err()) case <-time.After(duration): fmt.Printf("process request with %v, %d\n", duration, deep) } }