Golang producers and consumers

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

Using Golang can be easy to implement, producer and consumer functions.

Achieve one: (produce only a certain amount of data)

Write to private channel//write 10 func produce (p chan<-int) {for i: = 0; i <; i++ {p <-i//main thread cannot generate deadlock, so here is an error in FMT. Println ("Send:", i)}}//consumption dedicated channel//only take 10 func consumer (c <-chan int) {for i: = 0; I < 10; i++ {V: = <-cfmt. Println ("Receive:", V)}}

Call:

CH: = make (chan int)//only produce and consume 10 records go produce (CH) go Consumer (CH)

Implementation of two: (Automatic production and consumption)

Auto consumption func autoconsumer (ch <-chan int)  {    for{        Select {        case   ws:=<-ch:            fmt. Println ("FMT print", WS)        default: Time            . Sleep (1000*time.millisecond)}}}    

Call:

CH: = make (chan int)//continuous production and consumption, high up go func () {for{//continuous production, one time 10 produce (CH)}} () go Autoconsumer (CH)

Note: To keep the main process from dying, add this sentence at the bottom of the main function.

For  {        //Heartbeat time        . Sleep (time. Second)}

Good

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.