Golang / GoLang Concurrency Mastery Interview Questions
How does golang.org/x/sync/errgroup simplify concurrent error handling?
errgroup.Group is a higher-level abstraction over sync.WaitGroup that adds automatic error collection and optional context cancellation. It is the idiomatic tool for the pattern of running N goroutines and returning the first non-nil error.
import "golang.org/x/sync/errgroup"
// Basic errgroup — collect first error
func fetchAll(urls []string) error {
g := new(errgroup.Group)
for _, url := range urls {
url := url // capture for goroutine (pre-Go 1.22)
g.Go(func() error {
resp, err := http.Get(url)
if err != nil { return err }
defer resp.Body.Close()
return nil
})
}
return g.Wait() // waits for all; returns first non-nil error
}
// errgroup with context — cancel all on first error
func fetchWithCancel(ctx context.Context, urls []string) error {
g, gctx := errgroup.WithContext(ctx)
// gctx is cancelled when any goroutine returns an error
for _, url := range urls {
url := url
g.Go(func() error {
req, _ := http.NewRequestWithContext(gctx, "GET", url, nil)
resp, err := http.DefaultClient.Do(req)
if err != nil { return err }
defer resp.Body.Close()
return nil
})
}
return g.Wait()
}
// Limit concurrency (Go 1.20+)
g.SetLimit(10) // max 10 goroutines — g.Go blocks when at limit
for _, url := range urls {
url := url
g.Go(func() error { return fetch(url) })
}
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...
