Python同步隊列正確應用方式解析
我們今天將會通過Python同步隊列的相關介紹,來詳細分析一下這一編程語言中的多線程應用。希望對此又需要的朋友們可以通過本文介紹的內容充分的掌握這一應用技巧,以方便將來的實際應用。#t#
我們經常會采用生產者/消費者關系的兩個線程來處理一個共享緩沖區的數據。例如一個生產者線程接受用戶數據放入一個共享緩沖區里,等待一個消費者線程對數據 取出處理。但是如果緩沖區的太小而生產者和消費者兩個異步線程的速度不同時,容易出現一個線程等待另一個情況。為了盡可能的縮短共享資源并以相同速度工作 的各線程的等待時間,我們可以使用一個“隊列”來提供額外的緩沖區。
創建一個“隊列”對象
- 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異常。
我們用一個Python同步隊列例子來展示如何使用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()
Python同步隊列示例代碼中實現了兩個類:生產者類Producer和消費者類Consumer。前者在一個隨機的時間內放入一個值到隊列queue中然后顯示出來,后者在一定隨機的時間內從隊列queue中取出一個值并顯示出來。