-
Notifications
You must be signed in to change notification settings - Fork 15
二十四、channel的关闭和广播
wenjianzhang edited this page Nov 12, 2019
·
2 revisions
- 向关闭的 channel 发送数据,会导致 painc
- v,<-ok; ok 为 bool 值,true 表示正常接收,false 表示通道关闭
- 所有的 channel 接收者都会在 channel 关闭时,立刻从阻塞等待中返回且上述 ok 值为 false。这个广播机制常被利用,进行上多个订阅者同时发送信号。如:退出
示例代码
func dataProducer(ch chan int, wg *sync.WaitGroup) {
go func() {
for i := 0; i < 10;i++ {
ch <- i
}
close(ch)
wg.Done()
}()
}
func dataReceiver(ch chan int, wg *sync.WaitGroup) {
go func() {
for {
if data,ok := <-ch;ok {
fmt.Println(data)
}else {
break
}
}
wg.Done()
}()
}
func TestCloseChannel(t *testing.T) {
var wg sync.WaitGroup
ch := make(chan int)
wg.Add(1)
dataProducer(ch, &wg)
wg.Add(1)
dataReceiver(ch, &wg)
wg.Add(1)
dataReceiver(ch, &wg)
wg.Wait()
}
输出
=== RUN TestCloseChannel
1
2
3
4
0
6
7
8
9
5
--- PASS: TestCloseChannel (0.00s)
PASS
Process finished with exit code 0