Golang / GoLang Concurrency Mastery Interview Questions
Implement fan-out and fan-in concurrency patterns in Go.
Fan-out: distribute work from one source to multiple worker goroutines. Fan-in: merge results from multiple goroutines back into a single channel. Together they form Go's fundamental parallel pipeline pattern.
// Fan-out: distribute jobs to N workers func fanOut(ctx context.Context, jobs <-chan Job, workers int) []<-chan Result { outputs := make([]<-chan Result, workers) for i := 0; i < workers; i++ { out := make(chan Result) outputs[i] = out go func(o chan<- Result) { defer close(o) for { select { case <-ctx.Done(): return case job, ok := <-jobs: if !ok { return } o <- process(job) } } }(out) } return outputs } // Fan-in: merge N result channels into one func fanIn(ctx context.Context, channels ...<-chan Result) <-chan Result { var wg sync.WaitGroup merged := make(chan Result) forward := func(c <-chan Result) { defer wg.Done() for r := range c { select { case merged <- r: case <-ctx.Done(): return } } } wg.Add(len(channels)) for _, c := range channels { go forward(c) } go func() { wg.Wait(); close(merged) }() return merged } // Wire it together ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() jobs := make(chan Job, 100) go generateJobs(jobs) results := fanIn(ctx, fanOut(ctx, jobs, 8)...) for r := range results { fmt.Println(r) }
More Related questions...