当前位置:网站首页>Go from introduction to actual combat - task cancellation (note)
Go from introduction to actual combat - task cancellation (note)
2022-06-27 21:57:00 【Accumulated Ytu】
Task cancellation code display
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)
}
call cancel1(cancelChan)
call cancel2(cancelChan)
Only one method can be canceled channel
, If both are closed, you need to write more times, and the coupling is high ; Close by method 2 channel I can take all of them channel
close , Low coupling
边栏推荐
猜你喜欢
How to design an elegant caching function
Process control task
Experience sharing of meituan 20K Software Test Engineers
熊市慢慢,Bit.Store提供稳定Staking产品助你穿越牛熊
Go从入门到实战——Panic和recover(笔记)
Go from entry to practice - multiple selection and timeout control (notes)
Tiktok's interest in e-commerce has hit the traffic ceiling?
Bit.Store:熊市漫漫,稳定Staking产品或成主旋律
[LeetCode]动态规划解分割数组I[Red Fox]
I think I should start writing my own blog.
随机推荐
∫(0→1) ln(1+x) / (x² + 1) dx
How to design an elegant caching function
Go从入门到实战——多态(笔记)
Go从入门到实战——行为的定义和实现(笔记)
Sharing | intelligent environmental protection - ecological civilization informatization solution (PDF attached)
百万年薪独家专访,开发人员不修复bug怎么办?
软件缺陷管理——测试人员必会
STM32CubeIDE1.9.0\STM32CubeMX 6.5 F429IGT6加LAN8720A,配置ETH+LWIP
C language programming detailed version (learning note 1) I can't understand it after reading, and I can't help it.
Go从入门到实战——共享内存并发机制(笔记)
win11桌面出現“了解此圖片”如何删除
根据自定义excel标题模板快速excel导出
GBase 8a OLAP分析函数 cume_dist的使用样例
Test automatique de Test logiciel - test d'interface de l'introduction à la maîtrise, apprendre un peu chaque jour
不外泄的测试用例设计秘籍--模块测试
[LeetCode]515. Find the maximum value in each tree row
Dynamic refresh mapper
Simulink导出FMU模型文件方法
如何做好功能测试?你确定不想知道吗?
Go从入门到实战——所有任务完成(笔记)