Created
September 6, 2020 12:34
-
-
Save vitaliy-evsyukov/61399be368fa3b93b346bccdf1cf6fdf to your computer and use it in GitHub Desktop.
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 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