什麼是生產者消費者模式
在軟體開發的過程中,經常碰到這樣的場景:
某些模組負責生產資料,這些資料由其他模組來負責處理(此處的模組可能是:函式、執行緒、程式等)。產生資料的模組稱為生產者,而處理資料的模組稱為消費者。在生產者與消費者之間的緩衝區稱之為倉庫。生產者負責往倉庫運輸商品,而消費者負責從倉庫裡取出商品,這就構成了生產者消費者模式。
結構圖如下:
為了大家容易理解,我們舉一個寄信的例子。假設你要寄一封信,大致過程如下:
1、你把信寫好——相當於生產者生產資料
2、你把信放入郵箱——相當於生產者把資料放入緩衝區
3、郵遞員把信從郵箱取出,做相應處理——相當於消費者把資料取出緩衝區,處理資料
生產者消費者模式的優點
- 解耦
假設生產者和消費者分別是兩個執行緒。如果讓生產者直接呼叫消費者的某個方法,那麼生產者對於消費者就會產生依賴(也就是耦合)。如果未來消費者的程式碼發生變化,可能會影響到生產者的程式碼。而如果兩者都依賴於某個緩衝區,兩者之間不直接依賴,耦合也就相應降低了。
舉個例子,我們去郵局投遞信件,如果不使用郵箱(也就是緩衝區),你必須得把信直接交給郵遞員。有同學會說,直接給郵遞員不是挺簡單的嘛?其實不簡單,你必須 得認識誰是郵遞員,才能把信給他。這就產生了你和郵遞員之間的依賴(相當於生產者和消費者的強耦合)。萬一哪天郵遞員 換人了,你還要重新認識一下(相當於消費者變化導致修改生產者程式碼)。而郵箱相對來說比較固定,你依賴它的成本就比較低(相當於和緩衝區之間的弱耦合)。
- 併發
由於生產者與消費者是兩個獨立的併發體,他們之間是用緩衝區通訊的,生產者只需要往緩衝區裡丟資料,就可以繼續生產下一個資料,而消費者只需要從緩衝區拿資料即可,這樣就不會因為彼此的處理速度而發生阻塞。
繼續上面的例子,如果我們不使用郵箱,就得在郵局等郵遞員,直到他回來,把信件交給他,這期間我們啥事兒都不能幹(也就是生產者阻塞)。或者郵遞員得挨家挨戶問,誰要寄信(相當於消費者輪詢)。
- 支援忙閒不均
當生產者製造資料快的時候,消費者來不及處理,未處理的資料可以暫時存在緩衝區中,慢慢處理掉。而不至於因為消費者的效能造成資料丟失或影響生產者生產。
我們再拿寄信的例子,假設郵遞員一次只能帶走1000封信,萬一碰上情人節(或是聖誕節)送賀卡,需要寄出去的信超過了1000封,這時候郵箱這個緩衝區就派上用場了。郵遞員把來不及帶走的信暫存在郵箱中,等下次過來時再拿走。
通過上面的介紹大家應該已經明白了生產者消費者模式。
Python中的多執行緒程式設計
在實現生產者消費者模式之前,我們先學習下Python中的多執行緒程式設計。
執行緒是作業系統直接支援的執行單元,高階語言通常都內建多執行緒的支援,Python也不例外,並且Python的執行緒是真正的Posix Thread,而不是模擬出來的執行緒。
Python的標準庫提供了兩個模組:_thread和threading,_thread是低階模組,threading是高階模組,對_thread進行了封裝。絕大多數情況下,我們只需要使用threading這個高階模組。
下面我們先看一段在Python中實現多執行緒的程式碼。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import time,threading #執行緒程式碼 class TaskThread(threading.Thread): def __init__(self,name): threading.Thread.__init__(self,name=name) def run(self): print('thread %s is running...' % self.getName()) for i in range(6): print('thread %s >>> %s' % (self.getName(), i)) time.sleep(1) print('thread %s finished.' % self.getName()) taskthread = TaskThread('TaskThread') taskthread.start() taskthread.join() |
下面是程式的執行結果:
1 2 3 4 5 6 7 8 |
thread TaskThread is running... thread TaskThread >>> 0 thread TaskThread >>> 1 thread TaskThread >>> 2 thread TaskThread >>> 3 thread TaskThread >>> 4 thread TaskThread >>> 5 thread TaskThread finished. |
TaskThread類繼承自threading模組中的Thread執行緒類。建構函式的name引數指定執行緒的名字,通過過載基類run函式實現具體任務。
在簡單熟悉了Python的執行緒後,下面我們實現一個生產者消費者模shi。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
from Queue import Queue import random,threading,time #生產者類 class Producer(threading.Thread): def __init__(self, name,queue): threading.Thread.__init__(self, name=name) self.data=queue def run(self): for i in range(5): print("%s is producing %d to the queue!" % (self.getName(), i)) self.data.put(i) time.sleep(random.randrange(10)/5) print("%s finished!" % self.getName()) #消費者類 class Consumer(threading.Thread): def __init__(self,name,queue): threading.Thread.__init__(self,name=name) self.data=queue def run(self): for i in range(5): val = self.data.get() print("%s is consuming. %d in the queue is consumed!" % (self.getName(),val)) time.sleep(random.randrange(10)) print("%s finished!" % self.getName()) def main(): queue = Queue() producer = Producer('Producer',queue) consumer = Consumer('Consumer',queue) producer.start() consumer.start() producer.join() consumer.join() print 'All threads finished!' if __name__ == '__main__': main() |
執行結果可能如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Producer is producing 0 to the queue! Consumer is consuming. 0 in the queue is consumed! Producer is producing 1 to the queue! Producer is producing 2 to the queue! Consumer is consuming. 1 in the queue is consumed! Consumer is consuming. 2 in the queue is consumed! Producer is producing 3 to the queue! Producer is producing 4 to the queue! Producer finished! Consumer is consuming. 3 in the queue is consumed! Consumer is consuming. 4 in the queue is consumed! Consumer finished! All threads finished! |
因為多執行緒是搶佔式執行的,所以列印出的執行結果不一定和上面的完全一致。
小結
本例通過Python實現了一個簡單的生產者消費者模型。Python中的Queue模組已經提供了對執行緒同步的支援,所以本文並沒有涉及鎖、同步、死鎖等多執行緒問題。