-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathctx1.go
103 lines (91 loc) · 1.7 KB
/
ctx1.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
package main
import (
"context"
"fmt"
"sync"
"time"
)
var(
ch1 = make(chan int)
ch2 = make(chan int)
ch3 = make(chan int)
wg = sync.WaitGroup{}
)
func sum(array []int) int {
result := 0
for _, v := range array {
result += v
}
return result
}
func main() {
ctx := context.Background()
ctx, _ = context.WithTimeout(ctx, 4*time.Second)
go Ctx1(ctx)
select {
case <- ctx.Done():
fmt.Println("main Failed", ctx.Err())
case ret := <- ch1:
fmt.Printf("result is %d", ret)
}
time.Sleep(10*time.Second)
}
func Ctx1(ctx context.Context){
wg.Add(4)
ctx, cancleFunc := context.WithCancel(ctx)
go Ctx2(ctx, cancleFunc)
go Ctx3(ctx, cancleFunc)
var lData []int
go func() {
select {
case s := <- ctx.Done():
fmt.Println("get data3 is err, ", ctx.Err(), s)
cancleFunc()
case data := <- ch3:
fmt.Println("get data3 Done", data)
lData = append(lData, data)
}
wg.Done()
}()
go func() {
select {
case s := <- ctx.Done():
fmt.Println("get data2 is err, ", ctx.Err(), s)
cancleFunc()
case data := <- ch2:
fmt.Println("get data2 Done", data)
lData = append(lData, data)
}
wg.Done()
}()
wg.Wait()
Sum := sum(lData)
fmt.Println(Sum, "done logic1.")
ch1 <- Sum
}
func Ctx2(ctx context.Context, f context.CancelFunc) {
fmt.Println("in Ctx2.")
select {
case <- ctx.Done():
//f()
fmt.Println("get cancle single 2")
return
case <- time.After(6*time.Second):
ch2 <- 10
}
fmt.Println("done Ctx2.")
wg.Done()
}
func Ctx3(ctx context.Context, f context.CancelFunc) {
fmt.Println("in Ctx3.")
select {
case <- ctx.Done():
//f()
fmt.Println("get cancle single 3")
return
case <- time.After(4*time.Second):
ch3 <- 12
}
fmt.Println("done Ctx3.")
wg.Done()
}