I have the following code:
package main
import (
"context"
"errors"
"fmt"
"math/rand"
"time"
"golang.org/x/sync/errgroup"
)
func someOperation() error {
time.Sleep(1 * time.Second)
is_error := rand.Int() % 2
if is_error == 0 {
return nil
} else {
fmt.Println("some error in someOperation")
return errors.New("some error")
}
}
func main() {
cancelCtx, cancel := context.WithCancel(context.Background())
defer cancel()
eg, _ := errgroup.WithContext(cancelCtx)
for i := 0; i < 10; i++ {
eg.Go(func() error {
err := someOperation()
if err != nil {
cancel()
return err
}
return nil
})
}
if err := eg.Wait(); err != nil {
fmt.Println("ocurred error")
}
fmt.Println("all done")
}
What I want is that if one of the goroutines that is executing someOperation fails, no more goroutines are tried to be created for the other operations. For example, if the 5th operation fails, no more goroutines will be launched for the 6th, 7th, 8th, 9th, 10th operation. Does my code achieve this goal?