Skip to content

Commit

Permalink
Fan out Fan in
Browse files Browse the repository at this point in the history
  • Loading branch information
aditya43 committed May 31, 2021
1 parent 8c83afd commit 04c4fc2
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions 07-data-pipelines/02-fan-out-fan-in/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// Squaring numbers.

package main

import (
"fmt"
"sync"
)

func generator(nums ...int) <-chan int {
out := make(chan int)
go func() {
for _, n := range nums {
out <- n
}
close(out)
}()
return out
}

func square(in <-chan int) <-chan int {
out := make(chan int)
go func() {
for n := range in {
out <- n * n
}
close(out)
}()
return out
}

func merge(cs ...<-chan int) <-chan int {
out := make(chan int)
var wg sync.WaitGroup

output := func(c <-chan int) {
for n := range c {
out <- n
}
wg.Done()
}

wg.Add(len(cs))
for _, c := range cs {
go output(c)
}

go func() {
wg.Wait()
close(out)
}()
return out
}

func main() {
in := generator(2, 3)

c1 := square(in)
c2 := square(in)

for n := range merge(c1, c2) {
fmt.Println(n)
}
}

0 comments on commit 04c4fc2

Please sign in to comment.