|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "time" |
| 7 | +) |
| 8 | + |
| 9 | +func C(ctx context.Context) error { |
| 10 | + fmt.Println(ctx.Value("key3")) |
| 11 | + select { |
| 12 | + // 结束时候做点什么 ... |
| 13 | + case <-ctx.Done(): |
| 14 | + return ctx.Err() |
| 15 | + default: |
| 16 | + // 没有结束 ... 执行 ... |
| 17 | + return nil |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +func B(ctx context.Context) int { |
| 22 | + fmt.Println(ctx.Value("key0")) |
| 23 | + fmt.Println(ctx.Value("key1")) |
| 24 | + ctx = context.WithValue(ctx, "key3", "value3") |
| 25 | + go fmt.Println(C(ctx)) |
| 26 | + select { |
| 27 | + // 结束时候做点什么 ... |
| 28 | + case <-ctx.Done(): |
| 29 | + return -2 |
| 30 | + default: |
| 31 | + // 没有结束 ... 执行 ... |
| 32 | + return 0 |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +func A(ctx context.Context) int { |
| 37 | + ctx = context.WithValue(ctx, "key0", "value0") |
| 38 | + ctx = context.WithValue(ctx, "key1", "value1") |
| 39 | + go fmt.Println(B(ctx)) |
| 40 | + select { |
| 41 | + // 结束时候做点什么 ... |
| 42 | + case <-ctx.Done(): |
| 43 | + return -1 |
| 44 | + default: |
| 45 | + // 没有结束 ... 执行 ... |
| 46 | + return 0 |
| 47 | + } |
| 48 | +} |
| 49 | +func main() { |
| 50 | + // 定时取消 |
| 51 | + // { |
| 52 | + // timeout := 3 * time.Second |
| 53 | + // ctx, _ := context.WithTimeout(context.Background(), timeout) |
| 54 | + // fmt.Println(Add(ctx)) |
| 55 | + // } |
| 56 | + |
| 57 | + // 手动取消 |
| 58 | + { |
| 59 | + ctx, cancel := context.WithCancel(context.Background()) |
| 60 | + go func() { |
| 61 | + time.Sleep(2 * time.Second) |
| 62 | + // 主动取消 |
| 63 | + cancel() |
| 64 | + }() |
| 65 | + fmt.Println(A(ctx)) |
| 66 | + } |
| 67 | + select {} |
| 68 | +} |
0 commit comments