记录 golang context
chenzuoqing Lv3

记录 golang context

有四种

  • context.WithCancel
    • 可取消的context
  • context.WithDeadline
    • 在某时间结束的context
  • context.WithTimeout(context.Background(), 2 * time.Second)
    • 设置超时的context,也返回 ctxcancel,可以等待自动超时,也可以提前执行cancelctx.Done都可以接收到值
  • context.WithValue

WithCancel示例

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package main

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

var wg sync.WaitGroup

func cpuInfo(ctx context.Context) {
defer wg.Done()

// 再生成子context,给memoryInfo,不接收cancel方法,当父context被cancel时也能接受到ctx.Done消息
ctx2, _ := context.WithCancel(ctx)
go memoryInfo(ctx2)

for {
select {
case <-ctx.Done():
fmt.Println("==> 退出CPU监控")
return
default:
time.Sleep(time.Second)
fmt.Println("获取CPU信息")
}
}
}

func memoryInfo(ctx context.Context) {
defer wg.Done()
for {
select {
case <-ctx.Done():
fmt.Println("==> 退出内存监控")
return
default:
time.Sleep(time.Second)
fmt.Println("获取内存信息")
}
}
}

func main() {
// 主goroutine生成父ctx,默认用Background生成父context
ctx, cancel := context.WithCancel(context.Background())
wg.Add(2)
go cpuInfo(ctx)

time.Sleep(time.Second * 5)

// 父context,调用cancel时,同时会调用基于此context创建的子context的cancel方法
// 这里的效果也就是一起退出
cancel()

wg.Wait()

}

输出

1
2
3
4
5
6
7
8
9
10
11
12
获取内存信息
获取CPU信息
获取CPU信息
获取内存信息
获取内存信息
获取CPU信息
获取CPU信息
获取内存信息
获取CPU信息
==> 退出CPU监控
获取内存信息
==> 退出内存监控

WithTimeout示例

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
28
29
30
31
32
33
34
35
36
37
38
39
package main

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

var wg sync.WaitGroup

func cpuInfo(ctx context.Context) {
defer wg.Done()

for {
select {
case <-ctx.Done():
fmt.Println("==> 退出CPU监控")
return
default:
time.Sleep(time.Second)
fmt.Println("获取CPU信息")
}
}
}

func main() {
// 主goroutine生成父ctx,默认用Background生成父context
// 也返回cancel,不调用不接收
ctx, _ := context.WithTimeout(context.Background(), time.Second*3)

wg.Add(1)
go cpuInfo(ctx)

// timeout context的cancel只能在未超时前执行
//cancel()

wg.Wait()
}

输出

1
2
3
4
获取CPU信息
获取CPU信息
获取CPU信息
==> 退出CPU监控
 Comments