Go language exercise: Channel Select timeout mechanism

Source: Internet
Author: User

1. Code

2. Operation

3. Analysis

1. Code

1  PackageMain2 3 Import (4"Time"5"FMT"6 )7 8Func waitFor (Ch chanint) {9Fmt. Println (time. Now (), "Writing ...")Ten Time . Sleep (1E9) OneCH <-10 AFmt. Println (time. Now (), "wrote ...") - } -  the Func Main () { -var a chanint= Make (chanint) -var b chanint= Make (chanint) -var ch chanint= Make (chanint) +  - go waitFor (CH) +  Avar rint= 0 atFmt. Println (time. Now (), "SELECT ...") - Select { -      Casex: = <-A: -Fmt. Println (time. Now (), "read from a ...") -R =x -      Casex: = <-B: inFmt. Println (time. Now (), "read from B ...") -R =x to      Casex: = <-Ch: +Fmt. Println (time. Now (), "read from CH ...") -R =x the     } *Fmt. Println (time. Now (), "Select over.., R =", R) $ Time . Sleep (1E9)Panax NotoginsengFmt. Println (time. Now (), "over..") -}

2. Operation

12 2015-07-19 00:35:23.859684465 +0800 CST Select ... 3 2015-07-19 00:35:23.861022451 +0800 CST writing ... 4 2015-07-19 00:35:24.864462549 +0800 CST wrote ... 5 2015-07-19 00:35:24.865185396 +0800 CST read from ch ... 6 2015-07-19 00:35:24.874655353 +0800 CST Select over:, r =  7 2015-07-19 00:35:25.888486739 +0800 CST over..

3. Analysis

1) Select in the main thread starts running, blocking waits for 3 channel in Select

2) write data to CH WAITFOR in thread (co-process)

3) Select receives data for reading

4) Main thread exit

Go language exercise: Channel Select timeout mechanism

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.