任务取消代码展示
func isCancelled(cancelChan chan struct{}) bool {
select {
case <-cancelChan:
return true
default:
return false
}
}
func cancel1(cancelChan chan struct{}) {
cancelChan <- struct{}{}
}
func cancel2(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, "Done")
}(i, cancelChan)
}
cancel2(cancelChan)
time.Sleep(time.Second * 1)
}
调用cancel1(cancelChan)
调用cancel2(cancelChan)
方法一只能取消一个channel
,如果都关闭需要多写几次耦合度高;通过方法二关闭channel可以将所有的channel
关闭,同时耦合度低