多进程-Pipe和Manager数据共享和传递
pipe.py#多进程数据传递接收和发送(类似socket)
from multiprocessing import Process,Pipe def f(conn): conn.send([42,None,"hello from child"]) conn.send([42, None, "hello from child2"]) print("from parent:",conn.recv()) if __name__ == '__main__': parent_conn, child_conn= Pipe() p=Process(target=f,args=(child_conn,)) p.start() print(parent_conn.recv()) print(parent_conn.recv()) parent_conn.send("狗胖咬死你!") p.join()
manger.py#多进程之间数据共享和传递(同时修改一份数据)
from multiprocessing import Process,Manager import os def f(d,l): d[os.getpid()]=os.getpid() l.append(os.getpid()) print(l) if __name__ =="__main__": with Manager() as manager: d= manager.dict()#生成一个字典可在多个进程中共享一份数据和传递 l =manager.list(range(5))#生成一个列表可在多个进程中共享一份数据和传递 p_list =[] for i in range(10): p =Process(target=f,args=(d,l)) p.start() p_list.append(p) for res in p_list: res.join() print(d) print(l)