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 a3b6cf9

Browse files
20220417
1 parent e8acbe6 commit a3b6cf9

File tree

2 files changed

+70
-1
lines changed

2 files changed

+70
-1
lines changed

‎README.md

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

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

62-
第26章 Context与任务取消
62+
[第26章 Context与任务取消](https://github.com/java-aodeng/golang-examples/blob/master/go-26/cancel_by_context_test.go)
6363

6464
第27章 只运行一次
6565

‎go-26/cancel_by_context_test.go

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package go_25
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"testing"
7+
"time"
8+
)
9+
10+
/*
11+
Context
12+
关联任务的取消,就是用来当前线程被取消,相关联的子线程也会被取消的场景
13+
- 根Context:通过context.Background()创建
14+
- 子Context:context.WithCancel(parentContext)创建
15+
ctx,cancel=context.WithCancel(context.Background())
16+
- 当前Context被取消时,基于他的子context都会被取消
17+
- 接受取消通知<-ctx.Done()
18+
19+
*/
20+
func isCancelled(ctx context.Context) bool {
21+
select {
22+
case <-ctx.Done():
23+
return true
24+
default:
25+
return false
26+
}
27+
}
28+
29+
func TestCancel(t *testing.T) {
30+
ctx, cancel := context.WithCancel(context.Background())
31+
for i := 0; i < 5; i++ {
32+
go func(i int, ctx context.Context) {
33+
for {
34+
if isCancelled(ctx) {
35+
fmt.Println("isCancelled")
36+
break
37+
}
38+
fmt.Println("isSleep")
39+
time.Sleep(time.Millisecond * 1)
40+
}
41+
fmt.Println(i, "Cancelled")
42+
}(i, ctx)
43+
}
44+
//关闭渠道 关闭之后上面多线程里面会自动关闭循环
45+
cancel()
46+
47+
time.Sleep(time.Second * 10)
48+
}
49+
50+
/*
51+
运行结果 执行cancel_2方法后关闭了渠道 多线程for循环里面就立马关闭了循环,注释掉cancel_2再执行,会for循环打印isSleep直到10秒后退出
52+
=== RUN TestCancel
53+
isCancelled
54+
3 Cancelled
55+
isCancelled
56+
4 Cancelled
57+
isCancelled
58+
1 Cancelled
59+
isCancelled
60+
2 Cancelled
61+
isCancelled
62+
0 Cancelled
63+
--- PASS: TestCancel (1.00s)
64+
PASS
65+
66+
67+
Process finished with the exit code 0
68+
69+
*/

0 commit comments

Comments
(0)

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