github.com/nibnait/go-learn@v0.0.0-20220227013611-dfa47ea6d2da/src/test/chapter/ch4/30_cancel_by_context_test.go (about) 1 package ch4 2 3 import ( 4 "context" 5 "fmt" 6 "testing" 7 "time" 8 ) 9 10 func isCancelled(ctx context.Context) bool { 11 select { 12 case <-ctx.Done(): 13 return true 14 default: 15 return false 16 } 17 } 18 19 func TestCancel(t *testing.T) { 20 ctx, cancel := context.WithCancel(context.Background()) 21 22 for i := 0; i < 5; i++ { 23 go func(i int, ctx context.Context) { 24 for { 25 if isCancelled(ctx) { 26 break 27 } 28 time.Sleep(time.Millisecond * 5) 29 } 30 fmt.Println(i, "Cancelled") 31 }(i, ctx) 32 } 33 34 cancel() 35 time.Sleep(time.Second * 1) 36 }