-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
66 lines (52 loc) · 965 Bytes
/
main.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
package main
import (
"context"
"fmt"
"os"
"os/signal"
"sync"
"time"
)
func newNormalContext() context.Context {
return context.Background()
}
func newGracefulContext() context.Context {
ctx, cancel := context.WithCancel(context.Background())
go func() {
sig := make(chan os.Signal)
signal.Notify(sig) // accept all signal
defer signal.Stop(sig)
select {
case <-ctx.Done():
case <-sig:
cancel()
}
fmt.Println("graceful shutdown")
}()
return ctx
}
func main() {
wg := sync.WaitGroup{}
wg.Add(1)
ctx := newGracefulContext()
//ctx := newNormalContext()
go func(ctx context.Context) {
defer wg.Done()
data := 0
fmt.Println(data)
// simulate the hard work, then set data of 1
time.Sleep(2 * time.Second)
data = 1
fmt.Println(data)
select {
case <-ctx.Done():
fmt.Println("skip following job")
return
default:
}
time.Sleep(2 * time.Second)
data = 2
fmt.Println(data)
}(ctx)
wg.Wait()
}