Go語言實現生產者消費者問題

2021-10-19 16:07:53 字數 1361 閱讀 9617

某個模組負責產生資料,這些資料由另乙個模組來負責處理(此處的模組是廣義的,可以是類、函式、執行緒、程序等)。產生資料的模組,就形象地稱為生產者;而處理資料的模組,就稱為消費者。

單單抽象出生產者和消費者,還夠不上是生產者/消費者模式。該模式還需要有乙個緩衝區處於生產者和消費者之間,作為乙個中介。生產者把資料放入緩衝區,而消費者從緩衝區取出資料。

利用生產者消費者模式,設計乙個簡單的問題並通過程式設計解決。

生產者:開啟乙個goroutine迴圈生成int64隨機數,傳送到jobchan

消費者:從jobchan中取出隨機數計算個位數的和,將結果傳送到resultchan

緩衝區:jobchan chan, resultchan chan

package main

import

("fmt"

"math/rand"

"sync"

"time"

)// 使用goroutine和channel實現乙個計算int64隨機數各位和的程式

type job struct

type result struct

// producer 生產者:負責產生資料並將其放入緩衝區jobchan, jobchan是乙個唯讀通道

func

producer

(jobchan chan

<-

*job, wg *sync.waitgroup)

jobchan <- newjob

// goroutine執行太快,在此減慢一下速度

time.

sleep

(time.microsecond *

100)}}

// consumer 消費者:負責從jobchan緩衝區中讀出資料,對資料處理後寫入resultchan緩衝區

func

consumer

(jobchan <-

chan

*job, resultchan chan

<-

*result, wg *sync.waitgroup)

newresult :=

&result

resultchan <- newresult }}

func

main()

// 3. 主goroutine從resultchan取出結果並列印在console

i :=

0for result :=

range resultchan

wg.wait()

}

GO語言實現生產者消費者模型

一 只使用channel實現package main import fmt math rand sync time 生產者函式 func producter index int ch chan int 消費者函式 func consumer index int ch chan int func ma...

生產者與消費者問題C語言實現

實驗目的 實現生產者 消費者問題的模擬,以便更好的理解此經典程序同步問題。生產者 消費者問題是典型的pv操作問題,假設系統中有乙個比較大的緩衝池,生產者的任務是只要緩衝池未滿就可以將生產出的產品放入其中,而消費者的任務是只要緩衝池未空就可以從緩衝池中拿走產品。緩衝池被占用時,任何程序都不能訪問。每乙...

生產者 消費者問題實現

include include include include include include define need p 2 生產者程序數 define need c 2 消費者程序數 define works p 10 每個生產者程序執行的次數 define works c 10 每個消費者程序...