The earlier select function was used to monitor a series of file handles, and once an IO operation occurred on one of the file handles, the select call would be returned. Golang directly supports select at the language level to handle asynchronous IO issues.
The select usage is similar to switch, as follows:
timeout : = make (Chan bool, 1)
CH: = Make (chanint)Select { Case<-Ch: Case<-timeout:fmt. Println ("timeout!")default: FMT. Println ("default case is running")}
As can be seen, after CH initialization, Case1 read failed, timeout also failed, because there is no data in the channel, jump directly to default execution and return.
Note that if there is no default,select will wait until a case statement is completed, that is, until the data is read successfully from CH or timeout, it is blocked.
Based on this mechanism, you can use Select to implement the channel read timeout mechanism
Package Mainimport ("FMT" " Time"Func Main () {timeout:= Make (chanBOOL,1) go func () {time. Sleep (3E9)//Sleep 3 secondsTimeout <-true} () Ch:= Make (chanint) Select { Case<-Ch: Case<-timeout:fmt. Println ("timeout!") }}
Note that this must not use default, otherwise the 3s timeout has not been directly executed DEFAULT,CASE2 will not be executed, the timeout mechanism will not be implemented. Timeout reads the data after a 3s timeout.
Use Select to determine if the channel is full
CH1: = Make (chanint,1) CH2:= Make (chanint,1)Select { Case<-ch1:fmt. Println ("ch1 Pop One element") Case<-ch2:fmt. Println ("CH2 Pop One element") default: FMT. Println ("default")}
If case1, Case2 are not executed, the CH1&CH2 is full, over ...
Golang's Select usage