Short-circuit new goroutines if an error already occured

This commit is contained in:
Dan Jones 2025-09-07 23:21:44 -05:00
commit 8640832a27
2 changed files with 55 additions and 7 deletions

View file

@ -98,6 +98,38 @@ func ExampleGroup_parallel() {
// video result for "golang"
}
// FirstError demonstrates that g.Go becomes a no-op if a previous g.Go
// has returned an error.
func ExampleGroup_firstError() {
err1 := errors.New("errgroup_test: 1")
err2 := errors.New("errgroup_test: 2")
g := new(errgroup.Group)
ch := make(chan struct{})
g.Go(func() error {
fmt.Printf("Returning %s\n", err1)
ch <- struct{}{}
return err1
})
<-ch
g.Go(func() error {
// This should never run
fmt.Printf("Returning %s\n", err2)
return err2
})
err := g.Wait()
fmt.Printf("Got %s\n", err)
// Output:
// Returning errgroup_test: 1
// Got errgroup_test: 1
}
func TestZeroGroup(t *testing.T) {
err1 := errors.New("errgroup_test: 1")
err2 := errors.New("errgroup_test: 2")
@ -256,6 +288,7 @@ func TestCancelCause(t *testing.T) {
{errs: []error{nil}, want: nil},
{errs: []error{errDoom}, want: errDoom},
{errs: []error{errDoom, nil}, want: errDoom},
{errs: []error{nil, errDoom}, want: errDoom},
}
for _, tc := range cases {