Last active
August 9, 2018 12:00
-
-
Save humamfauzi/e519b3d7a9e6c110c5e8a4ee026c52e6 to your computer and use it in GitHub Desktop.
Example of Using Fan In design pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
// Merge function is based from https://github.com/tmrts/go-patterns with little modification | |
import ( | |
"sync" | |
"fmt" | |
"math/rand" | |
) | |
func main(){ | |
size := 20 | |
massiveChannel := make([]chan int, size) | |
for o := 0; o < size; o++ { | |
massiveChannel[o] = channelArray(randomArray(size)...) | |
} | |
count := 0 | |
for v := range Merge(massiveChannel...) { | |
fmt.Printf("%d ", v) | |
count++ | |
if count%size == 0 { | |
fmt.Printf("\n") | |
} | |
} | |
} | |
func randomArray(n int) []int { | |
var wg sync.WaitGroup | |
array := make([]int, n) | |
wg.Add(n) | |
go func() { | |
for i := 0; i < n; i++ { | |
array[i] = rand.Intn(10) | |
wg.Done() | |
} | |
}() | |
wg.Wait() | |
fmt.Println(array) | |
return array | |
} | |
func channelArray(a ...int) chan int { | |
var wg sync.WaitGroup | |
channel := make(chan int, len(a)) | |
wg.Add(len(a)) | |
go func() { | |
for _, number := range a { | |
channel <- number | |
wg.Done() | |
} | |
}() | |
wg.Wait() | |
defer close(channel) | |
return channel | |
} | |
func Merge(cs ...chan int) <-chan int { | |
var wg sync.WaitGroup | |
out := make(chan int, 1) | |
send := func(c <-chan int) { | |
for n := range c { | |
out <- n | |
} | |
wg.Done() | |
} | |
wg.Add(len(cs)) | |
for _, c := range cs { | |
go send(c) | |
} | |
go func() { | |
wg.Wait() | |
close(out) | |
}() | |
return out | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment