| ▲ | danenania 2 days 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. |
|
| ▲ | c0balt 2 days ago | parent | next [-] |
| You would probably benefit from errgroup, https://pkg.go.dev/golang.org/x/sync/errgroup But channels already do the waiting part for you. |
| |
|
| ▲ | javier2 2 days ago | parent | prev [-] |
| How you handle err here? If you return, the go routines will leak |
| |
| ▲ | danenania 2 days ago | parent [-] | | Ah, good point—should be using a buffered channel to avoid that: errCh := make(chan error, len(urls))
| | |
| ▲ | unsnap_biceps 2 days ago | parent [-] | | buffered 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 2 days ago | parent [-] | | > 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). |
|
|
|