Python處理序間通訊Queue執行個體解析,pythonqueue
本文研究的主要是Python處理序間通訊Queue的相關執行個體,具體如下。
1.Queue使用方法:
- Queue.qsize():返回當前隊列包含的訊息數量;
- Queue.empty():如果隊列為空白,返回True,反之False ;
- Queue.full():如果隊列滿了,返回True,反之False;
- Queue.get():擷取隊列中的一條訊息,然後將其從列隊中移除,可傳參逾時時間長度。
- Queue.get_nowait():相當Queue.get(False),取不到值時觸發異常:Empty;
- Queue.put():將一個值添加進數列,可傳參逾時時間長度。
- Queue.put_nowait():相當於Queue.get(False),當隊列滿了時報錯:Full。
2.Queue使用執行個體:
來,上代碼:
#!/usr/bin/env python3import timefrom multiprocessing import Process,Queueq = Queue() #建立列隊,不傳數字表示列隊不限數量for i in range(11): q.put(i)def A(): while 1: try: num = q.get_nowait() print('我是進程A,取出數字:%d'%num) time.sleep(1) except : breakdef B(): while 1: try: num = q.get_nowait() print('我是進程B,取出數字:%d'%num) time.sleep(1) except : breakp1 = Process(target = A)p2 = Process(target = B)p1.start()p2.start()
此程式是在隊列中加入10個數字,然後用2個進程來取出。
運行結果:
我是進程A,取出數字:0
我是進程B,取出數字:1
我是進程A,取出數字:2
我是進程B,取出數字:3
我是進程A,取出數字:4
我是進程B,取出數字:5
我是進程B,取出數字:6
我是進程A,取出數字:7
我是進程B,取出數字:8
我是進程A,取出數字:9
我是進程B,取出數字:10
3.使用進程池Pool時,Queue會出錯,需要使用Manager.Queue:
上代碼
#!/usr/bin/env python3import timefrom multiprocessing import Pool,Manager,Queueq = Manager().Queue()for i in range(11): q.put(i)def A(i): num = q.get_nowait() print('我是進程%d,取出數字:%d'%(i,num)) time.sleep(1) pool = Pool(3)for i in range(10): pool.apply_async(A,(i,))pool.close()pool.join()
運行結果:
我是進程1,取出數字:0
我是進程0,取出數字:1
我是進程2,取出數字:2
我是進程4,取出數字:3
我是進程3,取出數字:4
我是進程5,取出數字:5
我是進程6,取出數字:6
我是進程7,取出數字:7
我是進程8,取出數字:8
我是進程9,取出數字:9
當把Manager().Queue()直接換成Queue(),可能會出現資源混亂,缺少進程。
4.主進程定義了一個Queue類型的變數,並作為Process的args參數傳給子進程processA和processB,兩個進程一個向隊列中寫資料,一個讀資料。
import timefrom multiprocessing import Process,QueueMSG_QUEUE = Queue(5)def startA(msgQueue): while True: if msgQueue.empty() > 0: print 'queue is empty %d' % (msgQueue.qsize()) else: msg = msgQueue.get() print 'get msg %s' % (msg,) time.sleep(1)def startB(msgQueue): while True: msgQueue.put('hello world') print 'put hello world queue size is %d' % (msgQueue.qsize(),) time.sleep(3)if __name__ == '__main__': processA = Process(target=startA,args=(MSG_QUEUE,)) processB = Process(target=startB,args=(MSG_QUEUE,)) processA.start() print 'processA start..' processB.start() print 'processB start..'
其列印的結果如下:
C:\Python27\python.exe E:/outofmemory/test/queuetest/queuetest.py
processA start..
processB start..
queue is empty 0
put hello world queue size is 1
get msg hello world
queue is empty 0
queue is empty 0
put hello world queue size is 1
get msg hello world
queue is empty 0
queue is empty 0
put hello world queue size is 1
總結
以上就是本文關於Python處理序間通訊Queue執行個體解析的全部內容,希望對大家有所協助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支援!