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 dc6aba4

Browse files
20220411
1 parent 5fe5f0a commit dc6aba4

File tree

2 files changed

+83
-1
lines changed

2 files changed

+83
-1
lines changed

‎README.md

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

5656
[第23章 多路由选择和超时](https://github.com/java-aodeng/golang-examples/blob/master/go-23/select_test.go)
5757

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

6060
第25章 任务的取消
6161

‎go-24/channel_close_test.go

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
package go_24
2+
3+
import (
4+
"fmt"
5+
"sync"
6+
"testing"
7+
)
8+
9+
/*
10+
channel的关闭
11+
- 向关闭的channel发送数据,会导致panic
12+
- v,ok<-ch;ok为bool值,true表示正常接受,false表示通道关闭
13+
- 所有的channel接收者都会再channel关闭时,立刻从阻塞等待中返回且上述ok值为false,这个广播机制常被利用,进行向多个订阅者同时发送信息。如:退出信号。
14+
15+
*/
16+
17+
//数据提供者 向chan里面传0-9的数据
18+
func dataProduct(ch chan int, wg *sync.WaitGroup) {
19+
go func() {
20+
for i := 0; i < 10; i++ {
21+
ch <- i
22+
}
23+
//执行完了,关闭chan
24+
close(ch)
25+
//ch<-11 向关闭的chan发消息会抛异常
26+
//线程安全,不是本节重点,看不懂忽略
27+
wg.Done()
28+
}()
29+
}
30+
31+
//数据消费者 取出chan里面0-9的数据 输出
32+
func dataReceiver(ch chan int, wg *sync.WaitGroup) {
33+
go func() {
34+
for {
35+
if data, ok := <-ch; ok {
36+
fmt.Println(data)
37+
} else {
38+
break
39+
}
40+
}
41+
wg.Done()
42+
}()
43+
}
44+
45+
//测试
46+
func TestCloseChannel(t *testing.T) {
47+
var wg sync.WaitGroup
48+
//这里创建的是普通chan,不会存关闭chan有缓存的问题
49+
ch := make(chan int)
50+
51+
//调用数据提供者 设置chan
52+
wg.Add(1)
53+
dataProduct(ch, &wg)
54+
55+
//调用数据消费者 消费赋值了的chan
56+
wg.Add(1)
57+
dataReceiver(ch, &wg)
58+
59+
//调用数据消费者 消费赋值了的chan
60+
wg.Add(1)
61+
dataReceiver(ch, &wg)
62+
wg.Wait()
63+
}
64+
65+
/*
66+
运行结果 可以看到输出顺序不一样,因为我们调用了两个消费者 还是很简单的东西
67+
=== RUN TestCloseChannel
68+
0
69+
1
70+
2
71+
3
72+
5
73+
6
74+
7
75+
8
76+
9
77+
4
78+
--- PASS: TestCloseChannel (0.00s)
79+
PASS
80+
81+
82+
*/

0 commit comments

Comments
(0)

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