This repository has been archived by the owner on Mar 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
context.go
119 lines (107 loc) · 2.21 KB
/
context.go
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
go worker(ctx, "worker1")
go worker(ctx, "worker2")
go worker(ctx, "worker3")
time.Sleep(2 * time.Second)
cancel()
time.Sleep(1 * time.Second)
fmt.Println("-----------")
ctxTimeout()
time.Sleep(2 * time.Second)
fmt.Println("-----------")
ctxCancel()
time.Sleep(2 * time.Second)
fmt.Println("-----------")
ctxValue()
time.Sleep(2 * time.Second)
fmt.Println("-----------")
ctxExtend()
time.Sleep(2 * time.Second)
}
func worker(ctx context.Context, name string) {
for {
select {
case <-ctx.Done():
fmt.Println(name, "is over")
return
default:
fmt.Println(name, "is running ")
time.Sleep(1 * time.Second)
}
}
}
func ctxCancel() {
ctx, cancel := context.WithCancel(context.Background())
go func(ctx context.Context) {
select {
case <-ctx.Done():
fmt.Println("cancel: ", ctx.Err())
case <-time.After(1 * time.Second):
fmt.Println("Time out")
}
}(ctx)
time.Sleep(300 * time.Millisecond)
cancel()
}
func ctxTimeout() {
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(1*time.Second))
defer cancel()
go func(ctx context.Context) {
select {
case <-ctx.Done():
fmt.Println("time: ", ctx.Err())
case <-time.After(2 * time.Second):
fmt.Println("Time out")
}
}(ctx)
time.Sleep(2 * time.Second)
}
func ctxValue() {
ctx := context.WithValue(context.Background(), "user", "liubo")
go func(ctx context.Context) {
v, ok := ctx.Value("user").(string)
if ok {
fmt.Println(v)
}
}(ctx)
time.Sleep(time.Second)
}
func ctxExtend() {
ctx, cancel := context.WithCancel(context.Background())
go parent(ctx, "parent")
time.Sleep(2 * time.Second)
cancel()
time.Sleep(time.Second)
}
func parent(ctx context.Context, name string) {
go child(ctx, "child")
for {
select {
case <-ctx.Done():
fmt.Println(name, " stop")
return
default:
fmt.Println(name, " running")
time.Sleep(500 * time.Millisecond)
}
}
}
func child(ctx context.Context, name string) {
for {
select {
case <-ctx.Done():
fmt.Println(name, " stop")
return
default:
fmt.Println(name, " running")
time.Sleep(500 * time.Millisecond)
}
}
}