进程Queue,实现进程传输的队列
1.Queue
from multiprocessing import Process, Queue
def f(q):
q.put('1')
q.put('2')
if __name__ == '__main__':
q = Queue() #主进程
p = Process(target=f, args=(q,)) #把队列q作为参数传入f中 p是子进程
p.start()
print(q.get())
Pipe 作为一个管道, Pipe()生成一个conn_parent, conn_childen,把其中一个给其他进程,就可以实现两个进程之间的传输
2.Pipe
from multiprocessing import Pipe, Process
def f(conn,):
conn.send('name')
conn.send('alex')
data = conn.recv()
print(data)
if __name__ == '__main__':
conn_parent, conn_childen = Pipe()
p = Process(target=f, args=(conn_childen, ))
p.start()
conn_parent.recv()
conn_parent.recv()
conn_parent.send('alex')
Manager 生成进程列表, 或者进程字典, 将这个进程字典或列表拷贝一份传递给其他进程。
3.Manager
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(1, 10))
p_list = []
for i in range(10):
p = Process(target=f, args=(d, l))
p.start()
p_list.append(p)
for t in p_list:
t.join()
print(d)
print(l)