Fan-in / fan-out
Fan-out starts several goroutines from one channel of work. Fan-in merges several channels into one. Together they are how Go pipelines parallelize a stage and then collect results.
Detailed Explanation
A pipeline stage is a function that receives on in and sends on out. Fan-out is N copies of that stage reading the same in (or each taking from a shared jobs channel). Fan-in is a loop that copies every input channel onto one out, with a WaitGroup so out closes after the last copy finishes.
Fan-out needs a close policy. If in is closed, every worker's range in ends. If you use a shared jobs channel, close it once after enqueue. Workers must not close in.
Fan-in must not close too early. Each merge goroutine sends to out. Only after all of them return do you close(out). A WaitGroup in a separate goroutine is the usual closer.
Order is gone. Parallel stages reorder results unless you tag items with an index and reorder (more machinery). If order matters, fan-out is the wrong tool, or you need a sequence number.
What it costs. Fan-out increases throughput until you saturate CPU or the next I/O. Fan-in adds copies and a merge goroutine. For CPU-bound stages, N around GOMAXPROCS is a start. For I/O, N can be higher. Always pass ctx so cancel stops the whole graph.
Code Examples
package main
import "sync"
func fanOut(n int, in <-chan int, fn func(int) int) []<-chan int {
outs := make([]<-chan int, n)
for i := 0; i < n; i++ {
out := make(chan int)
outs[i] = out
go func() {
defer close(out)
for v := range in {
out <- fn(v)
}
}()
}
return outs
}
func fanIn(cs ...<-chan int) <-chan int {
out := make(chan int)
var wg sync.WaitGroup
for _, c := range cs {
wg.Add(1)
go func(c <-chan int) {
defer wg.Done()
for v := range c {
out <- v
}
}(c)
}
go func() {
wg.Wait()
close(out)
}()
return out
}
func main() {
in := make(chan int)
go func() {
in <- 1
close(in)
}()
_ = fanIn(fanOut(2, in, func(v int) int { return v })...)
}Common Gotchas
Multiple close of `in` panics
one owner closes.
Results are unordered
add indexes if the caller needs the original sequence.
Closing `out` from a worker before siblings finish drops values or panics on sen
Closing `out` from a worker before siblings finish drops values or panics on send
All workers sharing one `in` is fan-out; each worker with its own `in` is just p
All workers sharing one `in` is fan-out; each worker with its own `in` is just parallel pipelines