Last active
April 8, 2018 11:19
-
-
Save just1689/fdebaf76cba123555fcf4959acde1301 to your computer and use it in GitHub Desktop.
Merge data from multiple channels
This file contains 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 merge(cs ...<-chan int) <-chan int { | |
var wg sync.WaitGroup | |
out := make(chan int) | |
// Start an output goroutine for each input channel in cs. output | |
// copies values from c to out until c is closed, then calls wg.Done. | |
output := func(c <-chan int) { | |
for n := range c { | |
out <- n | |
} | |
wg.Done() | |
} | |
wg.Add(len(cs)) | |
for _, c := range cs { | |
go output(c) | |
} | |
// Start a goroutine to close out once all the output goroutines are | |
// done. This must start after the wg.Add call. | |
go func() { | |
wg.Wait() | |
close(out) | |
}() | |
return out | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment