- 进程池之间的通信需要使用multiprocessing模块中的
Manager.Queue()
而不是multiprocessing模块中的Queue()否则会报错; - 同样需要将进程以参数的形式传入:
直接看代码了解执行过程:
from multiprocessing import Pool,Manager
import time
import os
def reader(q1):
print(F'reader启动子进程为:{os.getpid()}-父进程为:{os.getppid}---')
for i in range(q1.qsize()):
print(F'reader从queue中{q1.qsize()}读取数据-----{q1.get(i)}----')
def writer(q1):
print(F'writer启动子进程为:{os.getpid()}-父进程为:{os.getppid}---')
for i in range(8):
q1.put(i)
print(F'向queue中写入数据----{i}')
#创建一个进程池,池中有五个进程
if __name__ == '__main__':
print(F'开始执行{os.getpid()}')
q1 = Manager().Queue() #使用Manager中的Queue
po = Pool(2)
po.apply_async(writer,args=(q1,))
time.sleep(1) #先让我上面的任务向Queue存入数据,再让下面的任务从中取数据
po.apply_async(reader,args = (q1,))
po.close() #关闭进程池,不能在接受新任务
po.join() #等待子进程
print(F'主进程执行-----{os.getpid()}')
执行结果:
开始执行11532
writer启动子进程为:11344-父进程为:<built-in function getppid>---
向queue中写入数据----0
向queue中写入数据----1
向queue中写入数据----2
向queue中写入数据----3
向queue中写入数据----4
向queue中写入数据----5
向queue中写入数据----6
向queue中写入数据----7
reader启动子进程为:9164-父进程为:<built-in function getppid>---
reader从queue中8读取数据-----0----
reader从queue中7读取数据-----1----
reader从queue中6读取数据-----2----
reader从queue中5读取数据-----3----
reader从queue中4读取数据-----4----
reader从queue中3读取数据-----5----
reader从queue中2读取数据-----6----
reader从queue中1读取数据-----7----
主进程执行-----11532
各种通信队列Queue对比:
1.线程间通信
from queue import Queue,LifoQueue,PriorityQueue
Queue()
LifoQueue()
PriorityQueue()
2.进程间通信
from multiprocessing import Queue
Queue()
3.进程池通信
from multiprocessing import Manager
Manager().Queue()