所謂超時,比如上網瀏覽一些安全的網站,如果幾分鍾之后不做操作,那么就會讓你重新登錄。
就所謂有時候出現goroutine阻塞的情況,那么我們如何避免整個程序進入阻塞情況,這時候就可以用select來設置超時
package main import ( "fmt"
"time" ) func main() { ch := make(chan int) quit := make(chan bool) //新開一個協程
go func() { for { select { case num := <-ch: //如果有數據,下面打印。但是有可能ch一直沒數據
fmt.Println("num = ", num) case <-time.After(3 * time.Second): //上面的ch如果一直沒數據會阻塞,那么select也會檢測其他case條件,檢測到后3秒超時
fmt.Println("超時") quit <- true //寫入
} } }() //別忘了()
for i := 0; i < 5; i++ { ch <- i time.Sleep(time.Second) } <-quit //這里暫時阻塞,直到可讀
fmt.Println("程序結束") }
//這里注意觀察打印過程
num = 0 num = 1 num = 2 num = 3 num = 4 超時 程序結束
補充代碼
//防止讀取超時
select { case <- time.After(time.Second*2): println("read channel timeout") case i := <- ch: println(i) } //防止寫入超時
select { case <- time.After(time.Second *2): println("write channel timeout") case ch <- "hello": println("write ok") }