Understanding Golang Channel with producer consumers

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

Golang realize multi-producer and multi-consumer:

package mainimport (    "fmt"    "time")func consumer(cname string, ch chan int) {    for i := range ch {        fmt.Println("consumer--", cname, ":", i)    }    fmt.Println("ch closed.")}func producer(pname string, ch chan int) {    for i := 0; i < 4; i++ {        fmt.Println("producer--", pname, ":", i)        ch <- i    }}func main() {    //用channel来传递"产品", 不再需要自己去加锁维护一个全局的阻塞队列    data := make(chan int)    go producer("生产者1", data)    go producer("生产者2", data)    go consumer("消费者1", data)    go consumer("消费者2", data)    time.Sleep(10 * time.Second)    close(data)    time.Sleep(10 * time.Second)}

Operation Result:

D:/Go/pv/pv.exe  [D:/Go/pv]producer-- 生产者2 : 0producer-- 生产者2 : 1producer-- 生产者2 : 2producer-- 生产者1 : 0consumer-- 消费者2 : 1consumer-- 消费者2 : 2consumer-- 消费者2 : 0producer-- 生产者1 : 1producer-- 生产者1 : 2consumer-- 消费者2 : 1consumer-- 消费者2 : 2producer-- 生产者1 : 3consumer-- 消费者2 : 3consumer-- 消费者1 : 0producer-- 生产者2 : 3consumer-- 消费者2 : 3ch closed.ch closed.成功: 进程退出代码 0.

It can be seen that using Golang to achieve producer consumers is very simple, PV operation does not require a variety of lock unlock, The secret lies in the CSP model, that is, Golang advocated using communication instead of shared memory.

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.