更多学习笔记和示例代码请访问:github.com/wenjianzhan…
任务取消
利用channel close 的广播特性,可以对任务进行取消
func isCancelled(cancelChan chan struct{}) bool {
select {
case <-cancelChan:
return true
default:
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, "Cancelled")
}(i, cancelChan)
}
cancel_1(cancelChan)
time.Sleep(time.Second * 1)
}
输出
=== RUN TestCancel
4 Cancelled
--- PASS: TestCancel (1.00s)
PASS
Process finished with exit code 0
这时只取消了4 这个协程,因为只取消了1个,其他的都 break 掉了; 那我们对代码进行修改
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, "Cancelled")
}(i, cancelChan)
}
cancel_2(cancelChan)
time.Sleep(time.Second * 1)
}
输出
=== RUN TestCancel
1 Cancelled
4 Cancelled
2 Cancelled
3 Cancelled
0 Cancelled
--- PASS: TestCancel (1.00s)
PASS
Process finished with exit code 0
五个协程全部取消了
更多学习笔记和示例代码请访问:github.com/wenjianzhan…