暮色呼如
您可以使用上下文和错误组。一些类似的东西...package mainimport ( "context" "fmt" "math/rand" "os" "time" "golang.org/x/sync/errgroup")func doStuff(ctx context.Context, i int) error { count := 0 for ctx.Err() == nil { // do the stuff time.Sleep(time.Millisecond * time.Duration(rand.Intn(500))) count++ if count > 6 { // error condition fmt.Fprintf(os.Stdout, "%v reached count %v\n", i, count) return fmt.Errorf("Error %v, count %v\n", i, count) } } fmt.Fprintf(os.Stdout, "Killed %v @ count %v\n", i, count) return ctx.Err()}func main() { rand.Seed(int64(time.Now().Nanosecond())) ctxWc, _ := context.WithCancel(context.Background()) g, ctx := errgroup.WithContext(ctxWc) for i := 0; i < 5; i++ { i := i g.Go(func() error { return doStuff(ctx, i) }) } err := g.Wait() fmt.Println("The End") if err != nil { fmt.Println(err) }}