Skip to content

Instantly share code, notes, and snippets.

@vitaliy-evsyukov
Created September 6, 2020 12:34
Show Gist options
  • Save vitaliy-evsyukov/61399be368fa3b93b346bccdf1cf6fdf to your computer and use it in GitHub Desktop.
Save vitaliy-evsyukov/61399be368fa3b93b346bccdf1cf6fdf to your computer and use it in GitHub Desktop.
func Merge2Channels(fn func(int) int, in1 <-chan int, in2 <-chan int, out chan<- int, m int) {
var wg sync.WaitGroup
wg.Add(1)
res := make([]int, m*2)
n := 0
go func() {
defer wg.Done()
for i := 0; i < m; i++ {
v1 := <-in1
v2 := <-in2
wg.Add(1)
go func(pos int) {
defer wg.Done()
v := fn(v1)
res[pos] = v
}(n)
wg.Add(1)
go func(pos int) {
defer wg.Done()
v := fn(v2)
res[pos+1] = v
}(n)
n += 2
}
}()
go func() {
wg.Wait()
for i := 0; i < len(res); i += 2 {
out <- res[i] + res[i+1]
}
}()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment