今天在工做中發現了一個有趣的現象。golang
在一個select中設定了兩個定時器,原本預計哪一個定時器到達就運行相應指令的,可是發現最終只有時間最短的定時器一直獲得執行,其它定時器徹底沒有獲得執行。服務器
package main import ( "fmt" "time" ) func main(){ for i:=0; i< 3;i ++ { select{ case <-time.After(7*time.Second): fmt.Println("1 second") case <-time.After(5*time.Second): fmt.Println("8 seconds") } } }
服務器輸出是:spa
8 seconds
8 seconds 8 seconds
在stackoverflow上有人提到了,time.After每次都會返回一個新的channel,因此select不可能監測到新產生的channel:
https://stackoverflow.com/questions/39212333/how-can-i-use-time-after-and-default-in-golang
package main import ( "fmt" "time" ) func main(){ count := 0 timeout1 := time.After(7*time.Second) timeout2 := time.After(5*time.Second) for i:=0; i< 36; i++{ select{ case <-timeout1: fmt.Println(count, "7 second") case <-timeout2: fmt.Println(count, "5 seconds") default: fmt.Println(count, "Just wait") } count++ time.Sleep(1*time.Second) } }
0 Just wait
1 Just wait 2 Just wait 3 Just wait 4 Just wait 5 5 seconds 6 Just wait 7 7 second 8 Just wait 9 Just wait 10 Just wait 11 Just wait 12 Just wait 13 Just wait 14 Just wait 15 Just wait 16 Just wait 17 Just wait 18 Just wait 19 Just wait 20 Just wait 21 Just wait 22 Just wait 23 Just wait 24 Just wait 25 Just wait 26 Just wait 27 Just wait 28 Just wait 29 Just wait 30 Just wait 31 Just wait 32 Just wait 33 Just wait 34 Just wait 35 Just wait