前面介紹了互斥鎖和條件變量解決線程間的同步問題,并使用條件變量同步機制解決了生產(chǎn)者與消費者問題。
讓我們考慮更復雜的一種場景:產(chǎn)品是各不相同的。這時只記錄一個數(shù)量就不夠了,還需要記錄每個產(chǎn)品的細節(jié)。很容易想到需要用一個容器將這些產(chǎn)品記錄下來。
Python的Queue模塊中提供了同步的、線程安全的隊列類,包括FIFO(先入先出)隊列Queue,LIFO(后入先出)隊列LifoQueue,和優(yōu)先級隊列PriorityQueue。這些隊列都實現(xiàn)了鎖原語,能夠在多線程中直接使用??梢允褂藐犃衼韺崿F(xiàn)線程間的同步。
用FIFO隊列實現(xiàn)上述生產(chǎn)者與消費者問題的代碼如下:
#encoding=utf-8 import threading import time from Queue import Queue
class Producer(threading.Thread): def run(self): global queue count = 0 while True: for i in range(100): if queue.qsize() > 1000: pass else: count = count +1 msg = '生成產(chǎn)品'+str(count) queue.put(msg) print msg time.sleep(1)
class Consumer(threading.Thread): def run(self): global queue while True: for i in range(3): if queue.qsize() < 100: pass else: msg = self.name + '消費了 '+queue.get() print msg time.sleep(1)
queue = Queue()
def test(): for i in range(500): queue.put('初始產(chǎn)品'+str(i)) for i in range(2): p = Producer() p.start() for i in range(5): c = Consumer() c.start() if __name__ == '__main__': test()
|