-
Notifications
You must be signed in to change notification settings - Fork 287
/
main.go
93 lines (85 loc) · 1.64 KB
/
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
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
package main
import (
"context"
"log"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
func withContextFunc(ctx context.Context, f func()) context.Context {
ctx, cancel := context.WithCancel(ctx)
go func() {
c := make(chan os.Signal)
// register for interupt (Ctrl+C) and SIGTERM (docker)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL)
defer signal.Stop(c)
select {
case <-ctx.Done():
case <-c:
f()
cancel()
}
}()
return ctx
}
func main() {
jobChan := make(chan int, 100)
stopped := make(chan struct{})
finished := make(chan struct{})
wg := &sync.WaitGroup{}
ctx := withContextFunc(
context.Background(),
func() {
log.Println("stop the server")
close(stopped)
wg.Wait()
close(finished)
},
)
// create 4 workers to process job
for i := 0; i < 4; i++ {
go func(i int) {
log.Printf("start worker: %02d", i)
for {
select {
case <-finished:
log.Printf("stop worker: %02d", i)
return
default:
select {
case job := <-jobChan:
time.Sleep(time.Duration(job*100) * time.Millisecond)
log.Printf("worker: %02d, process job: %02d", i, job)
wg.Done()
default:
log.Printf("worker: %02d, no job", i)
time.Sleep(1 * time.Second)
}
}
}
}(i + 1)
}
// send job
go func() {
for i := 0; i < 50; i++ {
wg.Add(1)
select {
case jobChan <- i:
time.Sleep(100 * time.Millisecond)
log.Printf("send the job: %02d\n", i)
case <-stopped:
wg.Done()
log.Println("stoped send the job")
return
}
}
return
}()
select {
case <-ctx.Done():
time.Sleep(1 * time.Second)
log.Println("server down")
}
}