Go語言筆記
Select
Go裡面的Select
和Java Nio裡面的模式有點類似,就是一個執行緒(程序/協程)同時去監聽多個目標的狀態。在Go裡面,Select
可以讓一個Goroutine同時去監聽多個Channel是否到達準備狀態,例子如下:
timeOut := make(chan bool, 1) go func() { time.Sleep(time.Duration(time.Second * 5)) timeOut <- true }() timeOutNext := make(chan bool, 1) go func() { time.Sleep(time.Duration(time.Second * 10)) timeOutNext <- true }() select { case <-timeOut: fmt.Println("TimeOut After 5 Seconds!") case <-timeOutNext: fmt.Println("TimeOut After 10 Seconds!") }
上面程式碼執行時,Select
阻塞到timeOut
這個Channel收到輸入時就退出了,要讓Select
不退出,timeOutNext
這個Channel也有機會收到輸入時,需要像下面這樣寫:
timeOut := make(chan bool, 1) go func() { time.Sleep(time.Duration(time.Second * 5)) timeOut <- true }() timeOutNext := make(chan bool, 1) go func() { time.Sleep(time.Duration(time.Second * 10)) timeOutNext <- true }() for { select { case <-timeOut: fmt.Println("TimeOut After 5 Seconds!") case <-timeOutNext: fmt.Println("TimeOut After 10 Seconds!") } }