我們經常會采用生產者/消費者關系的兩個線程來處理一個共享緩沖區的數據。例如一個生產者線程接受用戶數據放入一個共享緩沖區里,等待一個消費者線程對數據取出處理。但是如果緩沖區的太小而生產者和消費者兩個異步線程的速度不同時,容易出現一個線程等待另一個情況。為了盡可能的縮短共享資源并以相同速度工作的各線程的等待時間,我們可以使用一個“隊列”來提供額外的緩沖區。
創建一個“隊列”對象
import Queue
myqueue = Queue.Queue(maxsize = 10)
Queue.Queue類即是一個隊列的同步實現。隊列長度可為無限或者有限。可通過
Queue的構造函數的可選參數
maxsize來設定隊列長度。如果
maxsize小于
1就表示隊列長度無限。
將一個值放入隊列中
myqueue.put(10)
調用隊列對象的
put()方法在隊尾插入一個項目。
put()有兩個參數,第一個
item為必需的,為插入項目的值;第二個
block為可選參數,默認為
1。如果隊列當前為空且
block為
1,
put()方法就使調用線程暫停,直到空出一個數據單元。如果
block為
0,
put方法將引發
Full異常。
將一個值從隊列中取出
myqueue.get()
調用隊列對象的
get()方法從隊頭刪除并返回一個項目。可選參數為
block,默認為
1。如果隊列為空且
block為
1,
get()就使調用線程暫停,直至有項目可用。如果
block為0,隊列將引發
Empty異常。
我們用一個例子來展示如何使用
Queue
# queue_example.py
from Queue import Queue
import threading
import random
import time
# Producer thread
class Producer(threading.Thread):
def __init__(self, threadname, queue):
threading.Thread.__init__(self, name = threadname)
self.sharedata = queue
def run(self):
for i in range(20):
print self.getName(),'adding',i,'to queue'
self.sharedata.put(i)
time.sleep(random.randrange(10)/10.0)
print self.getName(),'Finished'
# Consumer thread
class Consumer(threading.Thread):
def __init__(self, threadname, queue):
threading.Thread.__init__(self, name = threadname)
self.sharedata = queue
def run(self):
for i in range(20):
print self.getName(),'got a value:',self.sharedata.get()
time.sleep(random.randrange(10)/10.0)
print self.getName(),'Finished'
# Main thread
def main():
queue = Queue()
producer = Producer('Producer', queue)
consumer = Consumer('Consumer', queue)
print 'Starting threads ...'
producer.start()
consumer.start()
producer.join()
consumer.join()
print 'All threads have terminated.'
if __name__ == '__main__':
main()
示例代碼中實現了兩個類:生產者類Producer和消費者類Consumer。前者在一個隨機的時間內放入一個值到隊列queue中然后顯示出來,后者在一定隨機的時間內從隊列queue中取出一個值并顯示出來。
posted on 2007-09-25 16:02
周銳 閱讀(509)
評論(0) 編輯 收藏 所屬分類:
Python