close版本
package ch20import ("fmt""testing""time"
)
func isCancelled(cancelChan chan struct{
}) bool {
select {
case <- cancelChan:return truedefault:return false}
}
func cancel_1(cancelChan chan struct{
}) {
cancelChan <- struct{
}{
}
}
func cancel_2(cancelChan chan struct{
}) {
close(cancelChan)
}func TestCancel(t *testing.T) {
cancelChan := make(chan struct{
},0)for i:=0;i<5;i++{
go func(i int,cancelCh chan struct{
}) {
for{
if isCancelled(cancelCh){
break}time.Sleep(time.Millisecond *5)}fmt.Println(i,"Cancel")}(i,cancelChan)}cancel_2(cancelChan)time.Sleep(time.Second*1)
}
context 版本
package contextimport ("context""fmt""testing""time"
)
func isCancelled(ctx context.Context) bool {
select {
case <- ctx.Done():return truedefault:return false}
}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,"Cancel")}(i,ctx)}cancel()time.Sleep(time.Second*1)
}