python使用Queue进行进程间通讯

1.Process之间有时须要通讯,操做系统提供了不少机制来实现进程间的通讯.python

可使用multiprocessing模块的Queue实现多进程之间的数据传递,app

Queue自己是一个消息列队程序:dom

from multiprocessing import Queue
q=Queue(3)  # 初始化一个Queue对象,最多可接收三条put消息
q.put("消息1")
q.put("消息2")
print(q.full())  # False
q.put("消息3")
print(q.full())  # True
# 由于消息列队已满下面的try都会抛出异常,
# 第一个try会等待2秒后再抛出异常,第二个Try会马上抛出异
try:
    q.put("消息4",True,2)
except:
    print("消息列队已满,现有消息数量:%s"%q.qsize())

try:
    q.put_nowait("消息4")
except:
    print("消息列队已满,现有消息数量:%s"%q.qsize())
# 推荐的方式,先判断消息列队是否已满,再写入
if not q.full():
    q.put_nowait("消息4")
# 读取消息时,先判断消息列队是否为空,再读取
if not q.empty():
    for i in range(q.qsize()):
        print(q.get_nowait())

2.初始化Queue()对象时(例如:q=Queue()),若括号中没有指定最大可接收的消息数量,spa

那么就表明可接受的消息数量没有上限(直到内存的尽头);操作系统

Queue.qsize():返回当前队列包含的消息数量;.net

Queue.empty():若是队列为空,返回True,反之False;code

Queue.full():若是队列满了,返回True,反之False;对象

Queue.get([block[, timeout]]):获取队列中的一条消息,而后将其从列队中移除,block默认值为True;blog

a.若是block使用默认值,且没有设置timeout(单位秒),消息列队若是为空,
此时程序将被阻塞,停在读取状态,直到从消息列队读到消息为止,若是设置了timeout,
则会等待timeout秒,若还没读取到任何消息,则抛出”Queue.Empty”异常;
b.若是block值为False,消息列队若是为空,则会马上抛出”Queue.Empty”异常;
Queue.get_nowait()--至关Queue.get(False);
若是block使用默认值,且没有设置timeout(单位秒),消息列队若是已经没有空间可写入,
此时程序将被阻塞(停在写入状态),直到从消息列队腾出空间为止,
若是设置了timeout,则会等待timeout秒,若还没空间,则抛出”Queue.Full”异常;
若是block值为False,消息列队若是没有空间可写入,则会马上抛出”Queue.Full”异常;
Queue.put_nowait(item)--至关Queue.put(item, False);

3.在父进程中建立两个子进程,一个往Queue里写数据,一个从Queue里读数据:队列

from multiprocessing import Process, Queue
import os, time, random
# 写数据进程执行的代码:
def write(q):
    for value in ['A', 'B', 'C']:
	print('Put %s to queue...' % value)
	q.put(value)
	time.sleep(random.random())
# 读数据进程执行的代码:
def read(q):
    while True:
	    if not q.empty():
		    value = q.get(True)
			print('Get %s from queue.' % value)
			time.sleep(random.random())
	    else:
		    break

if __name__=='__main__':
    # 父进程建立Queue,并传给各个子进程:
    q = Queue()
    pw = Process(target=write, args=(q,))
    pr = Process(target=read, args=(q,))
	# 启动子进程pw,写入
    pw.start()    
    # 等待pw结束:
    pw.join()
    # 启动子进程pr,读取:
    pr.start()
    pr.join()
    # pr进程里是死循环,没法等待其结束,只能强行终止:
    print('')
    print('全部数据都写入而且读完')

4.进程池中的Queue

若是要使用Pool建立进程,就须要使用multiprocessing.Manager()中的Queue(),
而不是multiprocessing.Queue(),不然会获得一条以下的错误信息:
RuntimeError: Queue objects should only be shared between processes through inheritance.

5.下面的实例演示了进程池中的进程如何通讯:

# 修改import中的Queue为Manager
from multiprocessing import Manager,Pool
import os,time,random

def reader(q):
    print("reader启动(%s),父进程为(%s)"%(os.getpid(),os.getppid()))
    for i in range(q.qsize()):
        print("reader从Queue获取到消息:%s"%q.get(True))

def writer(q):
    print("writer启动(%s),父进程为(%s)"%(os.getpid(),os.getppid()))
    for i in "dongGe":
        q.put(i)

if __name__=="__main__":
    print("(%s) start"%os.getpid())
    q=Manager().Queue() #使用Manager中的Queue来初始化
    po=Pool()
    #使用阻塞模式建立进程,这样就不须要在reader中使用死循环了,可让writer彻底执行完成后,再用reader去读取
    po.apply(writer,(q,))
    po.apply(reader,(q,))
    po.close()
    po.join()
    print("(%s) End"%os.getpid())

参考博客:https://blog.csdn.net/Duke10/article/details/79867656

相关文章
相关标签/搜索