python语言windows进程池中的Queue消息队列,进程通信

用进程池建立两个进程,实现进程间互相接收发送消息。

如果要使用Pool创建进程,就需要使用multiprocessing.Manager()中的Queue(),而不是multiprocessing.Queue(),否则会得到一条如下的错误信息:

RuntimeError: Queue objects should only be shared between processes through inheritance.

代码:

#coding=utf-8

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

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

def writer(q,q2):
    print("writer启动(%s),父进程为(%s)"%(os.getpid(),os.getppid()))
    xiaoxi=["在吗","明人不说暗话","还我钱"]
    for i in xiaoxi:
        q.put(i)

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

猜你喜欢

转载自blog.csdn.net/qq_36045385/article/details/81302905