-
Notifications
You must be signed in to change notification settings - Fork 95
Expand file tree
/
Copy pathctx.go
More file actions
67 lines (59 loc) · 1.45 KB
/
ctx.go
File metadata and controls
67 lines (59 loc) · 1.45 KB
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
61
62
63
64
65
66
67
package main
import (
"context"
"fmt"
"time"
)
// Tip: 通过 cancel 主动关闭
func ctxCancel() {
ctx, cancel := context.WithCancel(context.Background())
go func(ctx context.Context) {
select {
case <-ctx.Done():
fmt.Println(ctx.Err())
case <-time.After(time.Millisecond * 100):
fmt.Println("Time out")
}
}(ctx)
cancel()
}
// Tip: 通过超时,自动触发
func ctxTimeout() {
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*10)
// 主动执行cancel,也会让协程收到消息
defer cancel()
go func(ctx context.Context) {
select {
case <-ctx.Done():
fmt.Println(ctx.Err())
case <-time.After(time.Millisecond * 100):
fmt.Println("Time out")
}
}(ctx)
time.Sleep(time.Second)
}
// Tip: 通过设置截止时间,触发time out
func ctxDeadline() {
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(10*time.Millisecond))
defer cancel()
go func(ctx context.Context) {
select {
case <-ctx.Done():
fmt.Println(ctx.Err())
case <-time.After(time.Millisecond * 100):
fmt.Println("Time out")
}
}(ctx)
time.Sleep(time.Second)
}
// Tip: 用Key/Value传递参数,可以浅浅封装一层,转化为自己想要的结构体
func ctxValue() {
ctx := context.WithValue(context.Background(), "user", "junedayday")
go func(ctx context.Context) {
v, ok := ctx.Value("user").(string)
if ok {
fmt.Println("pass user value", v)
}
}(ctx)
time.Sleep(time.Second)
}