所有channel接收者都会在channel关闭时 立刻从阻塞等待中返回 ok值为false
这个广播机制经常被利用进行向多个订阅者同时发送信号 例如退出信号
func dowork() {
fmt.Println("do work.")
time.Sleep(time.Second)
}
func iscanceled(cancelchan chan struct{}) bool {
select {
case <-cancelchan:
return true
default:
return false
}
}
// 向cancelch中发送数据只能通知一个goroutine
func cancel1(cancelch chan struct{}) {
cancelch <- struct{}{}
}
// 关闭cancelch会通知所有从cancelch上接收数据的goroutine
func cancel2(cancelchan chan struct{}) {
close(cancelchan)
}
func main() {
cancelchan := make(chan struct{})
for i := 0; i < 5; i++ {
go func(i int, cancelch chan struct{}) {
for {
if iscanceled(cancelch) {
break
}
dowork()
}
fmt.Println(i, "canceled.")
}(i, cancelchan)
}
cancel2(cancelchan)
time.Sleep(time.Second * 3)
}