首页 > 编程语言 > 详细

python 多进程使用Queue通信的例子

时间:2014-09-01 13:50:53      阅读:306      评论:0      收藏:0      [点我收藏+]
import time
from multiprocessing import Process,Queue

MSG_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..

python2.6 test.py processA start.. queue is empty 0 processB start.. 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 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 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 get msg hello world queue is empty 0 queue is empty 0

主进程定义了一个Queue类型的变量,并作为Process的args参数传给子进程processA和processB,两个进程一个向队列中写数据,一个读数据。

其打印的结果如下:

 

python2.6 test.py 
processA start..
queue is empty 0
processB start..
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
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
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
get msg hello world
queue is empty 0
queue is empty 0

 

python 多进程使用Queue通信的例子

原文:http://www.cnblogs.com/stubborn412/p/3949030.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!