for select switch遍歷channel
之前在做測試的時候盖彭,寫過這樣一個協(xié)程的例子,運行之后發(fā)現(xiàn)Recive函數(shù)一直沒有退出
func main() {
flag := make(chan int,1)
msg := make(chan interface{},100)
go Send(msg)
go Recive(msg)
<-flag
}
func Send(msgChan chan interface{}) {
msgChan<-Msg{Name:"test"}
msgChan<-"close"
}
func Recive(msgChan chan interface{}) {
for {
select {
case msg := <-msgChan:
switch msg.(type) {
case Msg:
log.Println("type Msg",msg)
case string:
log.Println("type string",msg)
if msg=="close" {
close(msgChan)
break
}
}
default:
log.Println("select")
}
log.Println("for")
}
}
運行結(jié)果如下:
2019/09/12 22:08:46 type Msg {test}
2019/09/12 22:08:47 for
2019/09/12 22:08:47 type string close
2019/09/12 22:08:48 for
2019/09/12 22:08:49 for
2019/09/12 22:08:50 for
......
2019/09/12 22:10:28 for
發(fā)現(xiàn)Recive在接收到close的消息之后進行了break澳化,但是只是break出了select的代碼塊,for循環(huán)依然在運行稳吮,因此直接break是無法跳出for循環(huán)缎谷,需要使用break 標(biāo)簽這種方式來中斷
func Recive(msgChan chan interface{}) {
L:
for {
select {
case msg := <-msgChan:
switch msg.(type) {
case Msg:
log.Println("type Msg",msg)
case string:
log.Println("type string",msg)
if msg=="close" {
close(msgChan)
break L
}
}
default:
time.Sleep(time.Second)
log.Println("select")
}
time.Sleep(time.Second)
log.Println("for")
}
}