0%

context 相关知识与用法

父子 context cancel 的传递

以下测试可以简单验证父 context cancel 会传递到子 context,子 context cancel 不会影响父 context。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package main

import (
"fmt"
"context"
"time"
)

func main() {
ctx, cancel := context.WithCancel(context.Background())
newCtx, cancel1 := context.WithCancel(ctx)
go func(){
<-ctx.Done()
fmt.Printf("parent cancelled %s\n", time.Now())
}()
go func(){
<-newCtx.Done()
fmt.Printf("child cancelled %s\n", time.Now())
}()
time.Sleep(1*time.Second)
// cancel()
cancel1()
time.Sleep(10*time.Second)
// cancel1()
cancel()
time.Sleep(10*time.Second)
}
本文到此结束  感谢您的阅读