Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit fc9dd6d

Browse files
20220416
1 parent dc6aba4 commit fc9dd6d

File tree

2 files changed

+67
-1
lines changed

2 files changed

+67
-1
lines changed

‎README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ ps:白天上班,晚上更新,尽量日更,比心
5757

5858
[第24章 channel的关闭和广播](https://github.com/java-aodeng/golang-examples/blob/master/go-24/channel_close_test.go)
5959

60-
第25章 任务的取消
60+
[第25章 任务的取消](https://github.com/java-aodeng/golang-examples/blob/master/go-25/cancel_test.go)
6161

6262
第26章 Context与任务取消
6363

‎go-25/cancel_test.go

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package go_25
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
"time"
7+
)
8+
9+
func isCancelled(cancelChan chan struct{}) bool {
10+
select {
11+
case <-cancelChan:
12+
return true
13+
default:
14+
return false
15+
}
16+
}
17+
18+
func cancel_1(cancelChan chan struct{}) {
19+
cancelChan <- struct{}{}
20+
}
21+
22+
func cancel_2(cancelChan chan struct{}) {
23+
close(cancelChan)
24+
}
25+
26+
func TestCancel(t *testing.T) {
27+
cancelChan := make(chan struct{}, 0)
28+
for i := 0; i < 5; i++ {
29+
go func(i int, cacelCh chan struct{}) {
30+
for {
31+
if isCancelled(cancelChan) {
32+
fmt.Println("isCancelled")
33+
break
34+
}
35+
fmt.Println("isSleep")
36+
time.Sleep(time.Millisecond * 1)
37+
}
38+
fmt.Println(i, "Cancelled")
39+
}(i, cancelChan)
40+
}
41+
//关闭渠道 关闭之后上面多线程里面会自动关闭循环
42+
//cancel_2(cancelChan)
43+
44+
time.Sleep(time.Second * 10)
45+
}
46+
47+
/*
48+
运行结果 执行cancel_2方法后关闭了渠道 多线程for循环里面就立马关闭了循环,注释掉cancel_2再执行,会for循环打印isSleep直到10秒后退出
49+
=== RUN TestCancel
50+
isCancelled
51+
3 Cancelled
52+
isCancelled
53+
4 Cancelled
54+
isCancelled
55+
1 Cancelled
56+
isCancelled
57+
2 Cancelled
58+
isCancelled
59+
0 Cancelled
60+
--- PASS: TestCancel (1.00s)
61+
PASS
62+
63+
64+
Process finished with the exit code 0
65+
66+
*/

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /