How to Implement the Fan-Out/Fan-In Pattern in Go

Implement Fan-Out/Fan-In in Go by spawning goroutines to process items from a shared channel and sending results to a results channel, then closing the results channel once all workers finish.

How to Implement the Fan-Out/Fan-In Pattern in Go

Implement Fan-Out/Fan-In in Go by spawning goroutines to process items from a shared channel and sending results to a results channel, then closing the results channel once all workers finish.

package main

import (
	"fmt"
	"sync"
)

func worker(id int, jobs <-chan int, results chan<- int, wg *sync.WaitGroup) {
	defer wg.Done()
	for j := range jobs {
		results <- j * 2
	}
}

func main() {
	jobs := make(chan int, 100)
	results := make(chan int, 100)
	var wg sync.WaitGroup

	for w := 1; w <= 3; w++ {
		wg.Add(1)
		go worker(w, jobs, results, &wg)
	}

	go func() {
		for j := 1; j <= 10; j++ {
			jobs <- j
		}
		close(jobs)
		wg.Wait()
		close(results)
	}()

	for r := range results {
		fmt.Println(r)
	}
}