/
fan-in-and-fan-out.go
66 lines (55 loc) · 1.13 KB
/
fan-in-and-fan-out.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
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
func producer(id int, out chan<- int) {
for i := 0; i < 5; i++ {
value := rand.Intn(100)
fmt.Printf("Producer %d: Sending %d\n", id, value)
out <- value
time.Sleep(time.Millisecond * time.Duration(rand.Intn(1000)))
}
close(out)
}
func fanIn(inputs []<-chan int, out chan<- int) {
var wg sync.WaitGroup
wg.Add(len(inputs))
for _, input := range inputs {
go func(ch <-chan int) {
for value := range ch {
out <- value
}
wg.Done()
}(input)
}
go func() {
wg.Wait()
close(out)
}()
}
func main() {
rand.Seed(time.Now().UnixNano())
// Fan-Out
numProducers := 3
inputs := make([]chan int, numProducers)
for i := 0; i < numProducers; i++ {
inputs[i] = make(chan int)
go producer(i+1, inputs[i])
}
// Convert channels to <-chan int
inputChans := make([]<-chan int, numProducers)
for i := 0; i < numProducers; i++ {
inputChans[i] = inputs[i]
}
// Fan-In
result := make(chan int)
go fanIn(inputChans, result)
// Consume the merged values
for value := range result {
fmt.Printf("Consumer: Received %d\n", value)
}
fmt.Println("All done!")
}