所谓进程间通信,说白了就是不同的进程共同对一个变量进行修改
- manage进程间通信
# Author : Xuefeng
from multiprocessing import Manager, Process
import os
def f(d, l):
'''
定义修改变量的函数供创建进程使用
:param d: 共享的字典
:param l: 共享的列表
:return:
'''
d[1] = "hello"
d["2"] = "Jim"
d["a"] = "."
# 获取进程号并保存在共享列表中
l.append(os.getpid())
print(l)
if __name__ == "__main__":
with Manager() as manage:
# 创建共享字典
d = manage.dict()
# 创建共享列表
l = manage.list(range(5))
p_list = []
for i in range(10):
# 循环创建进程对共享变量进行更改
p = Process(target=f, args=(d, l))
p.start()
p_list.append(p)
for tmp in p_list:
# 等待所有进程结束
tmp.join()
# 打印最终的共享字典与列表
print("Final the dict:", d)
print("Final the list:", l)
- pipe进程间通信
# Author : Xuefeng
from multiprocessing import Process,Pipe
def f(conn):
'''
定义函数通过管道进行通信
:param conn: 传递数据给本管道
:return:
'''
# 用管道发送数据
conn.send([25,None,"Jim"])
conn.send([25,None,"Jim"])
conn.send([25,None,"Jim"])
# 打印管道接收到的数据
print(conn.recv())
# 关闭管道
conn.close()
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())
print(parent_conn.recv())
# 父管道向子管道传递消息
parent_conn.send("Hello, Jim")
p.join( )

被折叠的 条评论
为什么被折叠?



