python Queue队列例子

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:\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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值