Comment by danenania

Comment by danenania 11 hours ago

6 replies

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 11 hours ago

How you handle err here? If you return, the go routines will leak

  • danenania 11 hours ago

    Ah, good point—should be using a buffered channel to avoid that:

      errCh := make(chan error, len(urls))
    • unsnap_biceps 10 hours ago

      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 10 hours 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).