前言:
之前在學習操作系統的時候,就知道生產者-消費者,但是概念是模模糊糊的,好像是一直沒搞明白。
其實很簡單嘛,生產者生產,消費者進行消費,就是如此簡單。了解了一下go語言的goroute,感覺實現並發原來可以如此簡單,不像之前Java,什么還需要什么線程池啥的。
1、其實可以在一個go文件中可以實現的,按照go語言的開發習慣,按照標准的,定義三個包producer,consumer,main
2、producer.go
生產者每一秒產生一個header,一個隨機數,並將它輸出到管道pipe中。
package producer
import (
"fmt"
"math/rand"
"time"
)
func Produce(header string,pipe chan string ){
for{
pipe <- fmt.Sprintf("%s: %v",header,rand.Int31())
time.Sleep(time.Second)
}
}
3、consumer.go
消費者從管道拿到數據,並進行輸出。
package consumer
import("fmt")
func Consume(pipe chan string){
for{
message := <- pipe
fmt.Println(message)
}
}
4、main.go
a、main是可執行的入口,並且得有個main函數,make用於定義一個管道,供生產者寫入,消費者讀數據
b、在這么簡答的例子中,我們用到了go得並發特性,go是關鍵字,用於啟動一個goroute,下面的main函數中,啟動了兩個producer的goroute生產數據,consumer利用main函數的goroute進行消費,在main開始執行后,他們是並發執行的。
package main
import(
"consumer"
“producer"
)
func main(){
channel := make(chan string)
go producer.Produce("dog",channel)
go producer.Produce("cat",channel)
consumer.Consume(channel)
}
