Skip to content

Instantly share code, notes, and snippets.

@mannion007
Created February 28, 2020 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mannion007/882cd0198612cc04c592bee1458bc8a3 to your computer and use it in GitHub Desktop.
Save mannion007/882cd0198612cc04c592bee1458bc8a3 to your computer and use it in GitHub Desktop.
Fan in
package main
import (
"fmt"
"time"
"sync"
)
func main() {
r := fanIn(work(1), work(2))
for v := range r {
fmt.Println(v)
}
}
func work(sleepDur int) <-chan int {
c := make(chan int)
go func() {
for i := 0; i < 3; i++ {
c <- i
time.Sleep(time.Duration(sleepDur) * time.Second)
}
fmt.Println("done working")
close(c)
}()
return c
}
func fanIn(a, b <-chan int) <-chan int {
out := make(chan int)
var wg sync.WaitGroup
wg.Add(2)
go func() {
for {
o, ok := <-a
if !ok {
wg.Done()
break
}
out <- o
}
}()
go func() {
for {
o, ok := <-b
if !ok {
wg.Done()
break
}
out <- o
}
}()
go func() {
wg.Wait()
fmt.Println("Closing out")
close(out)
}()
return out
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment