Python 多进程编程之 进程间的通信(在Pool中Queue)
Python 多进程编程之 进程间的通信(在Pool中Queue)
1,在进程池中进程间的通信,原理与普通进程之间一样,只是引用的方法不同,python对进程池通信有专用的方法
在Manager()中引用Queue()方法来创建通信队列.
2,实例
from multiprocessing import Manager,Pool
def wp(q):
for i in "WANG":
q.put(i)
print("写入:%s"%i)
def rd(q):
while True:
if not q.empty():
print("读取:%s"%q.get())
if __name__=="__main__":
#创建队列,在进程池中专用方法,使用Manager中的Queue来初始化
qu = Manager().Queue()
#创建进程池,不做限制
po = Pool()
#创建写入进程
wp = po.apply(func=wp,args=(qu,))
#创建读取进程
rd = po.apply(func=rd,args=(qu,))
#关闭进程池
po.close()
3,执行结果
写入:W 写入:A 写入:N 写入:G 读取:W 读取:A 读取:N 读取:G
浙公网安备 33010602011771号