关联任务的取消
Contex
1、根Context:通过context.Background()创建
2、在Context:context.WithCancel(parentContext)创建
3、ctx,cancel := context.WithCancel(context.Background())
4、当前Context被取消时,基于它的子context都会被取消
5、接受取消通知 <-ctx.Done()
package ch4
import (
"context"
"fmt"
"testing"
"time"
)
func TestCancel(t * testing.T) {
ctx,cancel := context.WithCancel(context.Background())
for i := 0 ; i < 5 ; i++ {
go func(i int , ctx context.Context) {
for {
if isCancelled(ctx){
break
}
time.Sleep(time.Millisecond * 5)
}
fmt.Println(i,"Done")
}(i,ctx)
}
cancel()
time.Sleep(time.Second *1)
}
func isCancelled(ctx context.Context) bool {
select {
case <- ctx.Done():
return true
default:
return false
}
}