Golang Channel Select

Source: Internet
Author: User
Tags switch case
This is a creation in Article, where the information may have evolved or changed.

Support for channel in Golang added the Select keyword,

The implementation of channel Select in Golang is referenced by examples such as monitoring, timers, and so on http://blog.csdn.net/kjfcpua/article/details/18263839

The execution process is a bit like a switch case,case after the channel output can be received with a variable: num:=<-ch

If all the channel after the case has no output, then continue to follow the bad wait, if all the channel after the case has output, then randomly select a case execution.


However, there is a big difference between the for and for the bad, it should be added to the sleep mechanism, will not be full CPU, the following program monitoring program, with a for loop contrast.

1 package Main

2
3 Import (
4 "Time"
5)
6 var quit Chan int = make (chan int)
7 func loop (ch Chan int) {
8 Select {
9 Case &LT;-CH:
Ten case <-time. After (time. Duration (*time). Second): Quit <-0
11}
12}
Func gofor (ch Chan int) {
for{
_,ok:= <-ch;
If OK {
Break
18}
19}
20}
Func Main () {
CH: = make (chan int)
23/*
Close (CH)
Loop (CH)
<-quit
27 */
Gofor Go (CH)
Time. Sleep (10*time. Second)
ch<-0
31}

Results Analysis:

Execution channel SELECT:CPU occupies 0%


Execute for loop: 101% CPU consumption


Related Article

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.