3 ms·
I like WaitGroup as a concept, but I often end up using a channel instead for clearer error handling. Something like: errCh := make(chan error) for _, url
by danenania 1y ago
I like WaitGroup as a concept, but I often end up using a channel instead for clearer error handling. Something like:
errCh := make(chan error)
for _, url := range urls {
go func(url string){
errCh <- http.Get(url)
}(url)
}
for range urls {
err := <-errCh
if err != nil {
// handle error
}
}
Should I be using WaitGroup instead? If I do, don't I still need an error channel anyway—in which case it feels redundant? Or am I thinking about this wrong? I rarely encounter concurrency situations that the above pattern doesn't seem sufficient for.
- javier2 1y agoHow you handle err here? If you return, the go routines will leak
- danenania 1y agoAh, good point—should be using a buffered channel to avoid that: errCh := make(chan error, len(urls))
- unsnap_biceps 1y agobuffered channels won't help here. That's just how many results can be buffered before the remaining results can be added to the channel. It doesn't wait until all of them are done before returning a result to the consumer.
- danenania 1y ago> It doesn't wait until all of them are done before returning a result to the consumer. Right, but it prevents goroutine leaks. In these situations I'm usually fine with bailing on the first error, but I grant that's not always desirable. If it's not, I would collect and join errors and return those along with partial results (if those are useful).
- c0balt 1y agoYou would probably benefit from errgroup, https://pkg.go.dev/golang.org/x/sync/errgroup https://pkg.go.dev/golang.org/x/sync/errgroup But channels already do the waiting part for you.
- danenania 1y agoThanks! looking into errgroup