-
Notifications
You must be signed in to change notification settings - Fork 0
/
timeout3.go
61 lines (52 loc) · 858 Bytes
/
timeout3.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
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
// 控制多个任务
go work1(ctx)
go work2(ctx)
// 此处控制超时
time.Sleep(time.Second * 3)
cancel()
time.Sleep(time.Second * 2)
fmt.Println("end")
}
func work1(ctx context.Context) {
ctx2, _ := context.WithCancel(ctx)
go work3(ctx2)
for {
select {
case <-ctx.Done():
fmt.Println("work2 超时~")
return
case <-time.After(time.Second):
// block
}
}
}
func work3(ctx context.Context) {
for {
select {
case <-ctx.Done():
fmt.Println("work3 超时~")
return
case <-time.After(time.Second):
// block
}
}
}
func work2(ctx context.Context) {
for {
select {
case <-ctx.Done():
fmt.Println("work1 超时~")
return
case <-time.After(time.Second):
// block
}
}
}