Golang / GoLang Concurrency Mastery Interview Questions
Implement Go's canonical pipeline pattern with cancellation from the Go blog.
The Go blog defines three-stage pipelines: a generator that produces values, one or more transformation stages, and a consumer — all connected by directional channels, with cancellation via context.
// Stage 1: Generator
func generate(ctx context.Context, nums ...int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for _, n := range nums {
select {
case out <- n:
case <-ctx.Done(): return
}
}
}()
return out
}
// Stage 2: Transform
func square(ctx context.Context, in <-chan int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for v := range in {
select {
case out <- v * v:
case <-ctx.Done(): return
}
}
}()
return out
}
// Stage 3: Filter
func filterAbove(ctx context.Context, in <-chan int, min int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for v := range in {
if v <= min { continue }
select {
case out <- v:
case <-ctx.Done(): return
}
}
}()
return out
}
// Consumer
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
nums := generate(ctx, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
squares := square(ctx, nums)
results := filterAbove(ctx, squares, 25)
for i := 0; i < 3; i++ { fmt.Println(<-results) }
cancel() // stops all upstream stages cleanly
}
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...
