Go language exercise: Channel buffering mechanism

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

1. Code

2. Operation

3. Analysis

1. Code Buffer.go

1  PackageMain2 3 Import (4"FMT"5"Time"6 )7 8Func readthread (Ch chanint) {9Fmt. Println ("Read for reading ...")Ten      forI: =Range CH { OneFmt. Println ("Get I:", i) A         if20 = =I { -              Break -         }    the Time . Sleep (1e8) -     }    -Fmt. Println ("Read over ...") - } +  - Func Main () { +CH: = Make (chanint, 1024) A go readthread (CH) atTime. Sleep (1E9 * 2) -      forI: = 1; I <= 20; i++ { -CH <-I -     } -Fmt. Println ("Waitting for reading ...") -Time. Sleep (1E9 * 3) inFmt. Println ("Over ...") -}

2. Operation

1 $ go Run buffer.go2Read forreading ...3Waitting forreading ...4Get I:15Get I:26Get I:37Get I:48Get I:59Get I:6TenGet I:7 OneGet I:8 AGet I:9 -Get I:10 -Get I:11 theGet I:12 -Get I:13 -Get i:14 -Get i:15 +Get I:16 -Get i:17 +Get i:18 AGet i:19 atGet i:20 - Read over ... -Over ...

3. Analysis

Analysis based on the results of the operation:

1) First run Readthread read thread, read thread is ready to read, but at this time there is no data in the channel, so blocked. Wait for the read action.

2) The main thread, one-time to the channel to write a large amount of data, because of the buffer mechanism, so you can write multiple data at once without blocking. When the main thread finishes writing the data, it begins to wait for the read thread to end.

3) data is started in the channel, the read thread starts reading the data, reads one data every 0.1 seconds, reads 20 times altogether. Read finished, print read over.

4) Main thread wait time is up, return, exit

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.