当前位置:网站首页>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关闭,同时耦合度低
边栏推荐
- GoLand永久激活
- 本周二晚19:00战码先锋第8期直播丨如何多方位参与OpenHarmony开源贡献
- 通过CE修改器修改大型网络游戏
- Wechat applet based service management system for college party members' Home System applet graduation design, Party members, activists, learning, punch in, forum
- squid代理服務器
- 请教CMS小程序首页的幻灯片在哪里设置?
- 100 important knowledge points that SQL must master: sorting and retrieving data
- VMware vSphere esxi 7.0 installation tutorial
- 展现强劲产品综合实力 ,2022 款林肯飞行家Aviator西南首秀
- Go从入门到实战——CSP并发机制(笔记)
猜你喜欢

How to participate in openharmony code contribution

Show the comprehensive strength of strong products, and make the first show of 2022 Lincoln aviator in Southwest China

图解基于AQS队列实现的CountDownLatch和CyclicBarrier

Covering access to 2w+ traffic monitoring equipment, EMQ creates a new digital engine for all elements of traffic in Shenzhen

Focus! Tips for installing fonts on domestic computers

Animal breeding production virtual simulation teaching system | Sinovel interactive

Yu Wenwen, Hu Xia and other stars take you to play with the party. Pipi app ignites your summer

Codeforces Round #719 (Div. 3)

体验Navicat Premium 16,无限重置试用14天方法(附源码)

银河麒麟系统局域网文件共享教程
随机推荐
展现强劲产品综合实力 ,2022 款林肯飞行家Aviator西南首秀
如何将队列里面的内容没秒钟执行一次优先级
Love math experiment | Issue 8 - building of Singapore house price prediction model
Go from entry to practice - dependency management (notes)
ARCS模型介绍
MySQL Express - day 1 - basic introduction
Codeforces Round #719 (Div. 3)
Codeforces Round #722 (Div. 2)
squid代理服务器
空指针异常
Codeforces Round #721 (Div. 2)
富文本 考试 填空题
SQL必需掌握的100个重要知识点:组合 WHERE 子句
ABC-Teleporter Setting-(思维+最短路)
VMware vSphere esxi 7.0 installation tutorial
oss上传调用的是哪个方法
MySQL performance optimization index function, hidden, prefix, hash index usage (2)
Can Oracle's CTAs bring constraints and other attributes to the new table?
MYSQL 性能优化 index 函数,隐藏,前缀,hash 索引 使用方法(2)
Oracle的CTAS能不能将约束等属性带到新表?