Fan out and fan in results
Fan out and fan in results
Fan-out distributes work across consumers. Fan-in combines multiple streams into one. Unlike broadcasting, receiving from a shared jobs channel gives each sent value to one receiver. Merge below forwards every value from separate finite sources to one output.
package main
import ( "fmt" "sort" "sync")
func merge(inputs ...<-chan int) <-chan int { out := make(chan int) var wg sync.WaitGroup for _, in := range inputs { wg.Add(1) go func(c <-chan int) { defer wg.Done() for n := range c { out <- n } }(in) } go func() { wg.Wait(); close(out) }() return out}func source(values ...int) <-chan int { c := make(chan int, len(values)) for _, n := range values { c <- n } close(c) return c}func main() { var all []int for n := range merge(source(1, 3), source(2, 4)) { all = append(all, n) } sort.Ints(all) fmt.Println(all)}Each forwarding goroutine preserves the order of its own source but the combined order is not fixed. WaitGroup counts forwarders, not values. The collector must keep receiving until close. This finite merge assumes non-nil inputs that eventually close; for an early-exiting receiver use the cancellation pattern in the next lesson.
Expected output:
[1 2 3 4]Preserve identity rather than arrival order
package main
import ( "fmt" "sync")
type Result struct{ Index, Value int }
func main() { out := make(chan Result, 2) var wg sync.WaitGroup for i, v := range []int{5, 3} { wg.Add(1) go func(i, v int) { defer wg.Done(); out <- Result{i, v * v} }(i, v) } wg.Wait() close(out) ordered := make([]int, 2) for r := range out { ordered[r.Index] = r.Value } fmt.Println(ordered)}Attach the original index when order matters. Here the buffer can hold every result (exactly two) before Wait; this is not a general replacement for concurrent draining. An index lets the collector restore order even when arrivals differ.
Expected output:
[25 9]Try it locally
Merge three finite sources [7], [], [7, 1], sort and print [1 7 7].
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Concurrency patterns 02: Fan out and fan in results
Check the lesson objective before moving on.
Does merging guarantee global arrival order?
How restore input order?