python 多进程使用Queue通信的实例代码

发布时间:2019-10-01编辑:脚本学堂
本文分享一个python多线程通信的例子,学习下python多线程使用Queue通信的方法,有需要的朋友参考下吧。

python 多进程使用Queue通信的例子。
代码:
 

复制代码 代码示例:

#!/bin/python
#
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..'

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

打印结果:
 

C:Python27python.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