Golang's Select usage

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.