python 进程之间的数据共享

时间:2023-03-09 03:33:40
python 进程之间的数据共享
 from multiprocessing import Process,Manager
import os
def f(d,n):
d[os.getpid()] = os.getppid()#对字典d添加键值对,子进程:父进程
n.append(os.getpid())#将子进程添加到列表里。 if __name__ == '__main__':
with Manager() as manager:#类似with open获得句柄
l = manager.dict()#用manager创建一个字典
n = manager.list(range(5))#用manager创建一个列表并自带5个数据。
p_list = []#创建空列表
for i in range(5):#创建5个进程进行for循环
p = Process(target=f,args=(l,n))
p.start()#启动进程
p_list.append(p)#将进程添加到列表p_list
for res in p_list:#循环列表中进程
res.join()#对进程进行关闭
print(l,n)#打印5个不同进程对字典和列表的修改结果。