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) }
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
