首页 > 代码库 > python 多进程使用Queue通信的例子
python 多进程使用Queue通信的例子
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..‘
python2.6 test.py processA start..queue is empty 0processB start..put hello world queue size is 1get msg hello worldqueue is empty 0queue is empty 0put hello world queue size is 1get msg hello worldqueue is empty 0queue is empty 0put hello world queue size is 1get msg hello worldqueue is empty 0queue is empty 0put hello world queue size is 1get msg hello worldqueue is empty 0queue is empty 0put hello world queue size is 1get msg hello worldqueue is empty 0queue is empty 0put hello world queue size is 1get msg hello worldqueue is empty 0queue is empty 0put hello world queue size is 1get msg hello worldqueue is empty 0queue is empty 0
主进程定义了一个Queue类型的变量,并作为Process的args参数传给子进程processA和processB,两个进程一个向队列中写数据,一个读数据。
其打印的结果如下:
python2.6 test.py processA start..queue is empty 0processB start..put hello world queue size is 1get msg hello worldqueue is empty 0queue is empty 0put hello world queue size is 1get msg hello worldqueue is empty 0queue is empty 0put hello world queue size is 1get msg hello worldqueue is empty 0queue is empty 0put hello world queue size is 1get msg hello worldqueue is empty 0queue is empty 0put hello world queue size is 1get msg hello worldqueue is empty 0queue is empty 0put hello world queue size is 1get msg hello worldqueue is empty 0queue is empty 0put hello world queue size is 1get msg hello worldqueue is empty 0queue is empty 0
python 多进程使用Queue通信的例子
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。