Last active
June 11, 2019 17:33
-
-
Save zianwar/ff30792a6ea60b46fa43e86c053ff51b to your computer and use it in GitHub Desktop.
Golang Fan-in concurrency pattern.
This file contains hidden or 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
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