進程Queue,實現進程傳輸的隊列 app
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, Managerimport osdef 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)