-
Notifications
You must be signed in to change notification settings - Fork 0
/
graceful-shutdown.go
94 lines (82 loc) · 1.86 KB
/
graceful-shutdown.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
package main
import (
"fmt"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
/*
Example that shows how to gracefully terminate goroutines:
. producer: flag in a normal for-loop
. consumer: specific channel
*/
func main() {
messageChannel := make(chan string, 1000)
consumer := &Consumer{
messageChannel: messageChannel,
quitChannel: make(chan bool),
}
go consumer.startConsumer()
defer consumer.stopConsumer()
producer := &Producer{
messageChannel: messageChannel,
produceFlag: true,
}
go producer.startProducer()
defer producer.stopProducer()
syscallCh := make(chan os.Signal, 3)
signal.Notify(syscallCh, syscall.SIGTERM, syscall.SIGINT, os.Interrupt)
<-syscallCh
fmt.Println("GLOBAL TERMINATION SIGNAL")
time.Sleep(5 * time.Second)
}
type Producer struct {
messageChannel chan string
produceFlag bool
produceFlagMutex sync.Mutex
}
func (p *Producer) startProducer() {
fmt.Println("START PRODUCER")
counter := 1
for {
message := fmt.Sprintf("Message number %d", counter)
fmt.Printf("producer sending message to channel: %s \n", message)
p.messageChannel <- message
counter++
time.Sleep(time.Second)
p.produceFlagMutex.Lock()
if !p.produceFlag {
fmt.Println("PROCUCER TEMRINATION SIGNAL")
break
}
p.produceFlagMutex.Unlock()
}
}
func (p *Producer) stopProducer() {
fmt.Println("STOP PROCUCER")
p.produceFlagMutex.Lock()
defer p.produceFlagMutex.Unlock()
p.produceFlag = false
}
type Consumer struct {
messageChannel chan string
quitChannel chan bool
}
func (c *Consumer) startConsumer() {
fmt.Println("START CONSUMER")
for {
select {
case message := <-c.messageChannel:
fmt.Printf("consumer received message: %s\n", message)
case <-c.quitChannel:
fmt.Println("CONSUMER TERMINATION SIGNAL")
break
}
}
}
func (c *Consumer) stopConsumer() {
fmt.Println("STOP CONSUMER")
c.quitChannel <- true
}