#Goroutines - Elegantly processing multiple tasks by for loop but waiting for result of first one
24 messages · Page 1 of 1 (latest)
Like logically it doesn't make sense
So you want to calc both getValue(1) and getValue(2), and if getValue(1) goes right, cancel getValue(2)?
You'll need to modify getValue to support canceling
that kind of thing is exactly what https://pkg.go.dev/golang.org/x/sync/errgroup is made for
if using errgroups, the "how" is by taking a context.Context and stopping work some time shortly after the context closes, typically by selecting on its Done() channel
taking that approach also doesn't tie you to errgroups, context is a broadly applicable cancellation mechanism
"pepper" depends on how getValue is structured, but that's roughly the idea, yes
aside from the entire program exiting, every goroutine has to return to end
you can't remotely stop a goroutine, you can only send a signal e.g. via context that it should stop
you can, but you don't need to, you can just pass the same context
it'll cancel everywhere at once
in particular, goroutines aren't "recursive," you create them within a function but their lifetime is not related
now, what errgroup in particular does is implement what we call structured concurrency, which essentially means that the lifetime of every goroutine created in an errgroup is the same as the lifetime of the errgroup itself
and that lets you be "recursive" in the sense that you can use another errgroup to manage the lifetime of your subsequent computation
or it lets you be "iterative" in the sense that the thing that runs the first errgroup can then use the result it gets to run another errgroup
(structured concurrency is very cool and good)
Honestly im lost in the sauce, good luck!
there are things here that don't really match up with each other, so it's a bit confusing
for a straightforward answer: https://cs.opensource.google/go/x/sync/+/refs/tags/v0.1.0:errgroup/errgroup.go;l=46
errgroup.WithContext is a wrapper around context.WithCancel that calls the cancelfunc when a function in the group returns a non-nil error
i'm not sure how you arrived at panic
the error handling is a convenience feature of errgroup, and is why it's called an "errgroup," but it's still a more precise interpretation of structured concurrency than e.g. sync.waitgroup
if you don't need the error handling part, it's not too hard to do what errgroup does using a waitgroup and a context or channel, but you're still just reimplementing most of what errgroup does