-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.go
More file actions
62 lines (53 loc) · 1.32 KB
/
context.go
File metadata and controls
62 lines (53 loc) · 1.32 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
package main
import (
"context"
"fmt"
"time"
)
func main() {
//TimeOutCtxDemo()
TestCancelCtxDemo()
}
func TestCancelCtxDemo() {
ctx, canel := context.WithCancel(context.Background())
go submission(ctx)
// do something
time.Sleep(2 * time.Second)
// happened error here ,cancel sub goroutine
canel()
fmt.Println("done!")
for {
}
}
func submission(ctx context.Context) {
// 这里也可以do something
for {
// 这里也可以do something
select {
case <-ctx.Done():
fmt.Println("being canceled!", ctx.Err())
return
default:
fmt.Println("do something in sub mission")
time.Sleep(1 * time.Second)
}
}
}
func TimeOutCtxDemo() {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
go handle(ctx, 500*time.Millisecond) // 这个goruntine的执行时间是500ms,所以是可以正常执行完成的
//go handle(ctx, 1500*time.Millisecond) // 这个goruntine的执行时间是1500ms,这个时候设置的TimeOut执行时间是1000ms,所以这个goroutine收到结束信号无法执行结束
select {
case <-ctx.Done():
fmt.Println("main", ctx.Err())
}
}
func handle(ctx context.Context, duration time.Duration) {
select {
case <-ctx.Done():
fmt.Println("handle", ctx.Err())
case <-time.After(duration):
fmt.Println("Process request with", duration)
}
}