本文研究的主要是Python進(jìn)程間通信Queue的相關(guān)實(shí)例,具體如下。
1.Queue使用方法:
2.Queue使用實(shí)例:
來,上代碼:
#!/usr/bin/env python/278686.html">python/291767.html">python/268397.html">python/278448.html">python3import timefrom multiprocessing import Process,Queueq = Queue() #創(chuàng)建列隊(duì),不傳數(shù)字表示列隊(duì)不限數(shù)量for i in range(11): q.put(i)def A(): while 1: try: num = q.get_nowait() print('我是進(jìn)程A,取出數(shù)字:%d'%num) time.sleep(1) except : breakdef B(): while 1: try: num = q.get_nowait() print('我是進(jìn)程B,取出數(shù)字:%d'%num) time.sleep(1) except : breakp1 = Process(target = A)p2 = Process(target = B)p1.start()p2.start()此程序是在隊(duì)列中加入10個(gè)數(shù)字,然后用2個(gè)進(jìn)程來取出。
運(yùn)行結(jié)果:
我是進(jìn)程A,取出數(shù)字:0
我是進(jìn)程B,取出數(shù)字:1
我是進(jìn)程A,取出數(shù)字:2
我是進(jìn)程B,取出數(shù)字:3
我是進(jìn)程A,取出數(shù)字:4
我是進(jìn)程B,取出數(shù)字:5
我是進(jìn)程B,取出數(shù)字:6
我是進(jìn)程A,取出數(shù)字:7
我是進(jìn)程B,取出數(shù)字:8
我是進(jìn)程A,取出數(shù)字:9
我是進(jìn)程B,取出數(shù)字:10
3.使用進(jìn)程池Pool時(shí),Queue會(huì)出錯(cuò),需要使用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('我是進(jìn)程%d,取出數(shù)字:%d'%(i,num)) time.sleep(1) pool = Pool(3)for i in range(10): pool.apply_async(A,(i,))pool.close()pool.join()運(yùn)行結(jié)果:
我是進(jìn)程1,取出數(shù)字:0
我是進(jìn)程0,取出數(shù)字:1
我是進(jìn)程2,取出數(shù)字:2
我是進(jìn)程4,取出數(shù)字:3
我是進(jìn)程3,取出數(shù)字:4
我是進(jìn)程5,取出數(shù)字:5
我是進(jìn)程6,取出數(shù)字:6
我是進(jìn)程7,取出數(shù)字:7
我是進(jìn)程8,取出數(shù)字:8
我是進(jìn)程9,取出數(shù)字:9
當(dāng)把Manager().Queue()直接換成Queue(),可能會(huì)出現(xiàn)資源混亂,缺少進(jìn)程。
4.主進(jìn)程定義了一個(gè)Queue類型的變量,并作為Process的args參數(shù)傳給子進(jìn)程processA和processB,兩個(gè)進(jìn)程一個(gè)向隊(duì)列中寫數(shù)據(jù),一個(gè)讀數(shù)據(jù)。
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..'
其打印的結(jié)果如下:
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
總結(jié)
以上就是本文關(guān)于Python進(jìn)程間通信Queue實(shí)例解析的全部?jī)?nèi)容,希望對(duì)大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對(duì)本站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選