python:生產者與消費者模型

來源:互聯網
上載者:User

標籤:迴圈   while   one   while迴圈   range   pytho   生產者和消費者   守護   rabbit   

1,生產者與消費者模型的矛盾在於資料供需的不平衡

import timeimport randomfrom multiprocessing import Queuefrom multiprocessing import Processdef producer(q,food):    for i in range(5):        q.put(‘%s-%s‘%(food,i))        print(‘生產了%s‘%food)        time.sleep(random.random())    q.put(None)    q.put(None)    q.put(None)#有三個消費者因此需要三個訊號def consumer(q,name):    while True:        food = q.get()        if food == None:break        print(‘%s 吃了 %s‘%(name,food))if __name__ == ‘__main__‘:    q = Queue()    p1 = Process(target=producer,args=(q,‘菠蘿蜜幹‘))    p1.start()    p2 = Process(target=producer, args=(q, ‘優酪乳‘))    p2.start()    c1 = Process(target=consumer, args=(q, ‘Rabbit‘))    c1.start()    c2 = Process(target=consumer, args=(q, ‘OrangeCat‘))    c2.start()    c3 = Process(target=consumer, args=(q, ‘CuiHua‘))    c3.start()
生產者消費者模型
1.消費者要處理多少資料是不確定的
2.所以只能用while迴圈來處理資料 ,但是while迴圈無法結束
3.需要生產者發送訊號
4.有多少個消費者 就需要發送多少個訊號
5.但是發送的訊號數量需要根據 生產者和消費者的數量進行計算,所以非常不方便
2,JoinableQueue
import timeimport randomfrom multiprocessing import Processfrom multiprocessing import JoinableQueuedef producer(q,food):    for i in range(5):        q.put(‘%s-%s‘%(food,i))        print(‘生產了%s‘%food)        time.sleep(random.random())    q.join()  # 等待消費者把所有的資料都處理完def consumer(q,name):    while True:        food = q.get()   # 生產者不生產還是生產的慢        print(‘%s 吃了 %s‘%(name,food))        q.task_done()#JoinableQueue內部內建計數功能,每執行一次task_done,計數減一。
if __name__ == ‘__main__‘:
q = JoinableQueue()
p1 = Process(target=producer,args=(q,‘炒河粉‘))
p1.start()
p2 = Process(target=producer, args=(q, ‘草莓‘))
p2.start()
c1 = Process(target=consumer, args=(q, ‘Rabbit‘))
c1.daemon = True
c1.start()
c2 = Process(target=consumer, args=(q, ‘Orange_Cat‘))
c2.daemon = True
c2.start()
c3 = Process(target=consumer, args=(q, ‘Teddy‘))
c3.daemon = True
c3.start()

p1.join() # 等待p1執行完畢
p2.join() # 等待p2執行完畢


生產者生產的資料全部被消費 —— 生產者進程結束 —— 主進程代碼執行結束 —— 消費者守護進程結束

python:生產者與消費者模型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.