Python之兩種模式的生產者消費者模型

2021-08-18 16:26:10 字數 1754 閱讀 9659

第一種使用queue佇列實現:

#生產者消費者模型  其實伺服器集群就是這個模型

# 這裡介紹的是非yield方法實現過程

import threading,time

import queue

q = queue.queue(maxsize=10)

defproducer

(anme):

# for i in range(10):

# q.put('骨頭%s'%i)

count = 1

while

true:

q.put('骨頭%s'%count)

print('生產了骨頭',count)

count += 1

time.sleep(1)

defconsumer

(name):

# while q.qsize() >0:

while

true:

print('[%s] 取到[%s] 並且吃了它...'%(name,q.get()))

time.sleep(1)

p = threading.thread(target=producer,args=('shenchanzhe',))

c = threading.thread(target=consumer,args=('xiaofeizhe01',))

c1 = threading.thread(target=consumer,args=('xiaofeizhe02',))

p.start()

c.start()

c1.start()

使用yield協程的方法來實現生產者和消費者:

#生產者和消費者,使用生成器的方式,就是乙個簡單的並行,

import time

# 這是乙個消費者 一直在等待完成吃包子的動作

defconsumer

(name):

print('%s準備吃包子了!'%name) #列印出對應的消費者的名字

while

true: #執行乙個死迴圈 實際上就是需要呼叫時才會執行,沒有呼叫就會停止在yield

baozi = yield

#在它就收到內容的時候後就把內容傳給baozi

print('包子【%s】來了,被【%s】吃了'%(baozi,name))

defproducer

(name):

c1 = consumer('a') #它只是把c1變成乙個生成器

c2 = consumer('b')

c1.__next__() #第乙個next只是會走到yield然後停止

c2.__next__()

print('老子開始做包子了')

for i in range(1,10):

time.sleep(1)

print('三秒做了兩個包子')

c1.send(i) #這一步其實就是呼叫next方法的同時傳乙個引數i給field接收,然後baozi=i

c2.send(i+1)

#其實這裡是這樣的,在send的時候只是繼續執行yield下面的語句,然後去去yield,再次停在這兒

# producer('aea')

c = consumer('aaa') #沒next一次就會將程式執行一次

c.__next__()

c.__next__()

c.__next__()

生產者消費者問題的兩種寫法

問題 乙個固定容量的同步容器,有get方法和put方法,和size 方法。n個生產者不斷往裡面put,m個消費者不斷從中get。方式一 object的wait和notify public class testpandc p i t.start try catch interruptedexcepti...

生產者與消費者的兩種方式

synchronized版,使用wait notify public class demo01 catch interruptedexception e 生產者 start 消費者a去購買商品 new thread catch interruptedexception e 消費者a start 消費...

用Python之 生產者消費者模式

在軟體開發的過程中,經常碰到這樣的場景 某些模組負責生產資料,這些資料由其他模組來負責處理 此處的模組可能是 函式 執行緒 程序等 1.產生資料的模組稱為生產者,2.處理資料的模組稱為消費者。3.在生產者與消費者之間的緩衝區稱之為倉庫。4.生產者負責往倉庫運輸商品,而消費者負責從倉庫裡取出商品,這就...