Fan-in in Go
Merging several channels into one, closing the result when all are done.
func merge(inputs ...<-chan int) <-chan int {
out := make(chan int)
var wg sync.WaitGroup
for _, input := range inputs {
wg.Go(func() {
for value := range input {
out <- value
}
})
}
go func() {
wg.Wait()
close(out)
}()
return out
}
How it works
- A goroutine per input copies into the shared output.
- A WaitGroup decides when it is safe to close the output.
- The closing goroutine must not be one of the copiers.
Keywords and builtins used here
chancloseforfuncgointmakerangereturnvar
The run, in numbers
- Lines
- 18
- Characters to type
- 234
- Tokens
- 74
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 40 seconds.
Step 3 of 5 in Patterns, step 21 of 25 in Concurrency.