-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.go
More file actions
65 lines (55 loc) · 1.1 KB
/
main.go
File metadata and controls
65 lines (55 loc) · 1.1 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
63
64
65
package main
import (
"fmt"
"math/rand"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
const processRoutines = 2
func main() {
var ch chan int
ch = make(chan int)
var wg sync.WaitGroup
// create 2 process to process data from the channel
for id := range processRoutines {
wg.Add(1)
go func(id int) {
// each processor prints the data besides its id
for {
i, ok := <-ch
if !ok {
// if channel is closed, we will close the processor
fmt.Printf("closed the processosr %d\n", id)
wg.Done()
return
}
fmt.Printf("process %d in %d\n", i, id)
}
}(id)
}
shutdown := make(chan int)
// produce data evey 1 second into the channel
go func() {
for {
time.Sleep(1 * time.Second)
fmt.Println("we have a new input")
// if we have any data in shutdonw channel then
// close ch or write new data to it.
select {
case <-shutdown:
close(ch)
default:
ch <- rand.Intn(10)
}
}
}()
// wait for termination signal
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGTERM, syscall.SIGINT)
<-quit
close(shutdown)
wg.Wait()
}