github.com/chain5j/chain5j-pkg@v1.0.7/pool/groupwork/group_test.go (about) 1 // Package groupwork 2 // 3 // @author: xwc1125 4 package groupwork 5 6 import ( 7 "context" 8 "errors" 9 "fmt" 10 "runtime" 11 "testing" 12 "time" 13 14 "golang.org/x/sync/errgroup" 15 ) 16 17 // forever 持续打印数字,直到ctx结束 18 func forever(ctx context.Context, i int) { 19 for { 20 select { 21 case <-ctx.Done(): 22 fmt.Println("forever stop now") 23 return 24 default: 25 } 26 time.Sleep(time.Second) 27 fmt.Printf("goroutine %d is runnint\n", i) 28 runtime.Gosched() 29 } 30 } 31 32 // delayError 5秒后报错 33 func delayError() error { 34 time.Sleep(time.Second * 5) 35 fmt.Println("dealyError return") 36 return errors.New("should stop now") 37 } 38 39 func TestGroup_Go(t *testing.T) { 40 g, ctx := errgroup.WithContext(context.Background()) 41 for i := 0; i < 2; i++ { 42 i := i 43 if i == 0 { 44 g.Go(delayError) 45 continue 46 } 47 g.Go(func() error { 48 forever(ctx, i) 49 return nil 50 }) 51 } 52 if err := g.Wait(); err != nil { 53 fmt.Println(err) 54 } 55 }