在Go語言中大年,實現(xiàn)IO多路復(fù)用通常使用select語句。select語句可以同時監(jiān)聽多個通道的數(shù)據(jù)流動,一旦其中任何一個通道準(zhǔn)備好進行通信翔试,select就會觸發(fā)相應(yīng)的case執(zhí)行轻要。
func main() {
fmt.Println("Hello world")
ch1 := make(chan string)
ch2 := make(chan string)
go func() {
time.Sleep(1 * time.Second)
ch1 <- "Hello channel 1"
}()
go func() {
time.Sleep(2 * time.Second)
ch2 <- "Hello channel 2"
}()
shouldContinue := true
for {
if !shouldContinue { // select 和 for 一同使用的時候,不能在select層直接break
break
}
select {
case msg := <-ch1:
fmt.Printf("Received %s\n", msg)
case msg := <-ch2:
fmt.Printf("Received %s\n", msg)
case <-time.After(5 * time.Second): // time out check
fmt.Println("Timeout")
shouldContinue = false
}
}
}
結(jié)果:
Hello world
Received Hello channel 1
Received Hello channel 2
Timeout