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
package main
import (
"fmt"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
func worker(jobs <-chan int) {
for job := range jobs {
fmt.Println(job)
time.Sleep(500 * time.Millisecond)
}
}
func main() {
jobs := make(chan int, 1000)
var wg sync.WaitGroup
// Spawn example workers
for i := 0; i < 3; i++ {
wg.Add(1)
go func(jobs <-chan int) {
defer wg.Done()
worker(jobs)
fmt.Println("Worker is done.")
}(jobs)
}
// Create example messages
for i := 0; i < 100; i++ {
jobs <- i
}
waitForSignal()
close(jobs)
fmt.Println("Closed jobs!")
wg.Wait()
}
func waitForSignal() {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, os.Interrupt)
signal.Notify(sigs, syscall.SIGTERM)
<-sigs
}