Skip to content

Instantly share code, notes, and snippets.

@ccampo133
Created September 12, 2022 19:19
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 ccampo133/d9215062087e7ea8ed3336281cad090f to your computer and use it in GitHub Desktop.
Save ccampo133/d9215062087e7ea8ed3336281cad090f to your computer and use it in GitHub Desktop.
Generic function to merge multiple channels into a single channel (fan-in)
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