Created
September 12, 2022 19:19
-
-
Save ccampo133/d9215062087e7ea8ed3336281cad090f to your computer and use it in GitHub Desktop.
Generic function to merge multiple channels into a single channel (fan-in)
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
package main | |
import ( | |
"sync" | |
) | |
// Adapted from https://go.dev/blog/pipelines | |
func mergeChannels[T any](channels ...<-chan T) chan T { | |
var wg sync.WaitGroup | |
wg.Add(len(channels)) | |
// Start an output goroutine for each input channel in channels. Values from | |
// each channel are piped to out until the channel is closed, then calls | |
// wg.Done. | |
out := make(chan T) | |
for _, channel := range channels { | |
go func(c <-chan T) { | |
for n := range c { | |
out <- n | |
} | |
wg.Done() | |
}(channel) | |
} | |
// 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