Skip to content

Instantly share code, notes, and snippets.

@zianwar
Last active June 11, 2019 17:33
Show Gist options
  • Save zianwar/ff30792a6ea60b46fa43e86c053ff51b to your computer and use it in GitHub Desktop.
Save zianwar/ff30792a6ea60b46fa43e86c053ff51b to your computer and use it in GitHub Desktop.
Golang Fan-in concurrency pattern.
func fanIn(chans ...<-chan int) chan int {
var wg sync.WaitGroup
c := make(chan int)
// Closure to send values from a channel
output := func(ch <-chan int) {
for n := range ch {
c <- n
}
wg.Done()
}
wg.Add(len(chans))
// send values on c via differnt goroutines
for _, ch := range chans {
go output(ch)
}
// wait for all goroutines to finish before closing the channel
go func() {
wg.Wait()
close(c)
}()
return c
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment