Does errgroup kills non_error_gouroutines

68 views
Skip to first unread message

Amarjeet Anand

unread,
May 27, 2020, 7:42:43 AM5/27/20
to golang-nuts
Code from https://pkg.go.dev/golang.org/x/sync/errgroup?tab=doc
var g errgroup.Group
var urls = []string{
"http://www.golang.org/",
"http://www.google.com/",
"http://www.somestupidname.com/",
}
for _, url := range urls {
url := url
g.Go(func() error {
// Fetch the URL.
resp, err := http.Get(url)
if err == nil {
resp.Body.Close()
}
return err
})
}
if err := g.Wait(); err == nil {
fmt.Println("Successfully fetched all URLs.")
}

Out of 3, suppose 2 Goroutines will keep running in parallel without error
and while calling “http://www.google.com/”, it got an error.
That will be collected at g.Wait().

My question is Does errgroup terminates the other 2 running Goroutines if the main keeps running?

Or I need to use errgroup.WithContext(ctx) and keep listening this context if its ctx.Done() and then terminate my goroutine??

Tamás Gulácsi

unread,
May 27, 2020, 8:52:08 AM5/27/20
to golang-nuts
errgroup does not terminate.
But will signal the (sub)context returned by WithContext when any goroutine returns with an error.

So if your functions handle the context cancelation by exiting, then you can cancel other goroutines.

I asvice using such sub context with requests, too.

Amarjeet Anand

unread,
May 27, 2020, 9:21:04 AM5/27/20
to Tamás Gulácsi, golang-nuts
Thanks for your response.
Got it.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/7d6b7a91-3af7-48d0-acf9-2bdcdb25e57d%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages