producer consumer problem implement with Go

生产者消费者问题(Producer–consumer problem)是一个典型的并发问题,生产者产生数据,同时消费者也在消费数据。

Go的特点就是并发性,所以实现这个问题对go来说很轻松。

package main
import "fmt"

var done = make(chan bool)
var products = make(chan int)

func producer() {
    for i := 0; i < 10; i++ {
        products <- i
        fmt.Println(i, " produced!")
    }
    done <- true
}

func consumer() {
    for {
        product := <- products
        fmt.Println(product, " consumed!")
    }
}

func main() {
    go producer();
    go consumer();
    <- done
}