Python同步隊列正確應(yīng)用方式解析
我們今天將會通過Python同步隊列的相關(guān)介紹,來詳細(xì)分析一下這一編程語言中的多線程應(yīng)用。希望對此又需要的朋友們可以通過本文介紹的內(nèi)容充分的掌握這一應(yīng)用技巧,以方便將來的實際應(yīng)用。#t#
我們經(jīng)常會采用生產(chǎn)者/消費者關(guān)系的兩個線程來處理一個共享緩沖區(qū)的數(shù)據(jù)。例如一個生產(chǎn)者線程接受用戶數(shù)據(jù)放入一個共享緩沖區(qū)里,等待一個消費者線程對數(shù)據(jù) 取出處理。但是如果緩沖區(qū)的太小而生產(chǎn)者和消費者兩個異步線程的速度不同時,容易出現(xiàn)一個線程等待另一個情況。為了盡可能的縮短共享資源并以相同速度工作 的各線程的等待時間,我們可以使用一個“隊列”來提供額外的緩沖區(qū)。
創(chuàng)建一個“隊列”對象
- import Queue
- myqueue = Queue.Queue(maxsize = 10)Queue.Queue
類即是一個隊列的同步實現(xiàn)。隊列長度可為無限或者有限??赏ㄟ^Queue的構(gòu)造函數(shù)的可選參數(shù)maxsize來設(shè)定隊列長度。如果maxsize小于1就表示隊列長度無限。
將一個值放入隊列中
- myqueue.put(10)
調(diào)用隊列對象的put()方法在隊尾插入一個項目。put()有兩個參數(shù),第一個item為必需的,為插入項目的值;第二個block為可選參數(shù),默認(rèn)為1。如果隊列當(dāng)前為空且block為1,put()方法就使調(diào)用線程暫停,直到空出一個數(shù)據(jù)單元。如果block為0,put方法將引發(fā)Full異常。
將一個值從隊列中取出
- myqueue.get()
調(diào)用隊列對象的get()方法從隊頭刪除并返回一個項目。可選參數(shù)為block,默認(rèn)為1。如果隊列為空且block為1,get()就使調(diào)用線程暫停,直至有項目可用。如果block為0,隊列將引發(fā)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同步隊列示例代碼中實現(xiàn)了兩個類:生產(chǎn)者類Producer和消費者類Consumer。前者在一個隨機(jī)的時間內(nèi)放入一個值到隊列queue中然后顯示出來,后者在一定隨機(jī)的時間內(nèi)從隊列queue中取出一個值并顯示出來。