mirror of
https://github.com/crazybber/awesome-patterns.git
synced 2024-11-25 14:26:04 +03:00
63 lines
1013 B
Go
63 lines
1013 B
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
)
|
||
|
|
||
|
func main() {
|
||
|
randomNumbers := []int{13, 44, 56, 99, 9, 45, 67, 90, 78, 23}
|
||
|
// generate the common channel with inputs
|
||
|
inputChan := generatePipeline(randomNumbers)
|
||
|
|
||
|
// Fan-out to 2 Go-routine
|
||
|
c1 := squareNumber(inputChan)
|
||
|
c2 := squareNumber(inputChan)
|
||
|
|
||
|
// Fan-in the resulting squared numbers
|
||
|
c := fanIn(c1, c2)
|
||
|
sum := 0
|
||
|
|
||
|
// Do the summation
|
||
|
for i := 0; i < len(randomNumbers); i++ {
|
||
|
sum += <-c
|
||
|
}
|
||
|
fmt.Printf("Total Sum of Squares: %d", sum)
|
||
|
}
|
||
|
|
||
|
func generatePipeline(numbers []int) <-chan int {
|
||
|
out := make(chan int)
|
||
|
go func() {
|
||
|
for _, n := range numbers {
|
||
|
out <- n
|
||
|
}
|
||
|
close(out)
|
||
|
}()
|
||
|
return out
|
||
|
}
|
||
|
|
||
|
func squareNumber(in <-chan int) <-chan int {
|
||
|
out := make(chan int)
|
||
|
go func() {
|
||
|
for n := range in {
|
||
|
out <- n * n
|
||
|
}
|
||
|
close(out)
|
||
|
}()
|
||
|
return out
|
||
|
}
|
||
|
|
||
|
func fanIn(input1, input2 <-chan int) <-chan int {
|
||
|
c := make(chan int)
|
||
|
go func() {
|
||
|
for {
|
||
|
select {
|
||
|
case s := <-input1:
|
||
|
c <- s
|
||
|
case s := <-input2:
|
||
|
c <- s
|
||
|
}
|
||
|
}
|
||
|
}()
|
||
|
return c
|
||
|
}
|