-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
114 lines (101 loc) · 2.44 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package main
import (
"fmt"
"runtime"
"sync"
"time"
)
// generator function creates a channel and generates numbers to send to the channel
// it listen on a 'done' to cancel generation if needed1
func generator(done <-chan struct{}, nums ...int) <-chan int {
out := make(chan int, len(nums))
go func() {
for _, n := range nums {
fmt.Printf("generator: sending %d\n", n)
select {
case out <- n:
case <-done:
fmt.Println("generator: canceled")
return
}
}
close(out)
}()
return out
}
// square function receives integers,square them, and sends them to an output channel
// it also listens for a cancellation signal via 'done' channel
func square(done <-chan struct{}, in <-chan int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for n := range in {
select {
case out <- n * n:
case <-done:
return
}
}
}()
return out
}
// merge function merges multiple channels into one output channel
// it listens on each input channel and sends data to 'out', with cancellation support
func merge(done <-chan struct{}, cs ...<-chan int) <-chan int {
out := make(chan int)
var wg sync.WaitGroup
// 'output' reads data from each input channel and sends it to 'out' channel
output := func(c <-chan int) {
defer wg.Done()
for n := range c {
select {
case out <- n:
case <-done:
return
}
}
}
wg.Add(len(cs))
for _, c := range cs {
go output(c)
}
go func() {
wg.Wait()
close(out)
}()
return out
}
// Flow work:
//
// [ Generator ] -----> [ In Channel ]
// | |
// v v
// Send 2, 3 Receive 2, 3
// | |
// v v
// [ Square (c1) ] [ Square (c2) ]
// | |
// v v
// Square 2, 3 Square 2, 3
// | |
// v v
// [ Merge ] <--------------------->
// |
// v
// Final output
func main() {
// 'done' channel for cancellation
done := make(chan struct{})
// start generator with input numbers 2 and 3
in := generator(done, 2, 3)
c1 := square(done, in)
c2 := square(done, in)
out := merge(done, c1, c2)
for v := range out {
fmt.Println("Result:", v)
}
close(done)
time.Sleep(time.Second)
g := runtime.NumGoroutine()
fmt.Printf("=> number of goroutine active = %d\n", g)
}