Golang / Golang Internals and Memory Management Interview Questions
How do you implement fan-out and fan-in patterns with Go goroutines?
Fan-out: one goroutine distributes work to multiple worker goroutines. Fan-in: multiple goroutines send results back to a single aggregator. Together they form Go's most common concurrency idiom for parallel pipelines.
// Fan-out / Fan-in pipeline
func generate(nums ...int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for _, n := range nums { out <- n }
}()
return out
}
func square(in <-chan int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for n := range in { out <- n * n }
}()
return out
}
// Fan-out: start N workers on the same input channel
func fanOut(in <-chan int, workers int) []<-chan int {
outs := make([]<-chan int, workers)
for i := 0; i < workers; i++ {
outs[i] = square(in) // each reads from the shared input
}
return outs
}
// Fan-in: merge N result channels into one
func fanIn(ctx context.Context, channels ...<-chan int) <-chan int {
var wg sync.WaitGroup
merged := make(chan int)
forward := func(c <-chan int) {
defer wg.Done()
for n := range c {
select {
case merged <- n:
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 up
nums := generate(1, 2, 3, 4, 5)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
results := fanIn(ctx, fanOut(nums, 3)...)
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...
