Go --- channel implements producer consumer, go --- channel producer

Source: Internet
Author: User

Go --- channel implements producer consumer, go --- channel producer

I. No buffer zone

Package main // unbuffered channelimport ("fmt" "time") func produce (ch chan <-int) {for I: = 0; I <10; I ++ {ch <-ifmt. println ("Send:", I)} func consumer (ch <-chan int) {for I: = 0; I <10; I ++ {v: = <-chfmt. println ("Receive:", v)} // when the producer assigns a value to the channel because the channel does not have a buffer, the producer thread is blocked, until the consumer thread extracts data from the channel // After the consumer extracts the data for the first time, the consumer's thread will be blocked during the next loop, because the producer has not stored the data, the program will execute the // producer thread. In this way, the program continuously switches between the consumer and the producer until the loop ends. Func main () {ch: = make (chan int) go produce (ch) go consumer (ch) time. Sleep (1 * time. Second )}

2. Buffer Zone

In this program, the buffer can store 10 int-type integers. during the execution of the producer thread, the thread will not be blocked. The 10 integers will be stored in the channel at a time. During reading, it is also a one-time read.

Package main // channelimport ("fmt" time ") func produce (ch chan <-int) {for I: = 0; I <10; I ++ {ch <-ifmt. println ("Send:", I)} func consumer (ch <-chan int) {for I: = 0; I <10; I ++ {v: = <-chfmt. println ("Receive:", v)} func main () {ch: = make (chan int, 10) go produce (ch) time. sleep (1 * time. second )}


View comments

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.