当前位置:网站首页>Go从入门到实战——任务的取消(笔记)
Go从入门到实战——任务的取消(笔记)
2022-06-27 19:23:00 【积淀 ytu】
任务取消代码展示
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关闭,同时耦合度低
边栏推荐
猜你喜欢

Industry case | see the operation of bank digital transformation from the king of retail

流程控制任务

White whoring red team goby & POC, how do you call white whoring?

JPA踩坑系列之save方法

VMware vSphere ESXi 7.0安装教程

Go从入门到实战——协程机制(笔记)

MySQL performance optimization index function, hidden, prefix, hash index usage (2)

SQL server for circular usage

Go从入门到实战——接口(笔记)

GFS分布式文件系统
随机推荐
Acwing周赛57-最长连续子序列-(二分or树状数组)
100 important knowledge points that SQL must master: creating calculation fields
Shell command used in actual work - sed
Contest 2050 and Codeforces Round #718 (Div. 1 + Div. 2)
VMware vSphere ESXi 7.0安装教程
Focus! Tips for installing fonts on domestic computers
Love math experiment | phase 9 - intelligent health diagnosis using machine learning method
JPA踩坑系列之save方法
快递e栈——数组篇小型项目
ICML2022 | 可扩展深度高斯马尔可夫随机场
GoLand永久激活
Share how I take notes
体验Navicat Premium 16,无限重置试用14天方法(附源码)
Can Oracle's CTAs bring constraints and other attributes to the new table?
华为伙伴暨开发者大会2022开源时刻全纪录
Covering access to 2w+ traffic monitoring equipment, EMQ creates a new digital engine for all elements of traffic in Shenzhen
展现强劲产品综合实力 ,2022 款林肯飞行家Aviator西南首秀
SQL必需掌握的100个重要知识点:用通配符进行过滤
Flexible IP network test tool -- x-launch
Original translation | comparison of machine learning model service tools: kserve, Seldon core and bentoml