· 进程与进程之间是相互独立的,它们之间的数据交互需要有一个中间介质。
代码范例1:父进程与子进程之间的数据交互(Queue)
import multiprocessing def f(qq): qq.put([32,'oldboy','man']) if __name__ == '__main__': q = multiprocessing.Queue() p = multiprocessing.Process(target=f,args=(q,)) p.start() print(q.get()) # 输出:[32, 'oldboy', 'man']
代码范例2:进程与进程之间的数据交互(Pipe)
from multiprocessing import Process, Pipe def f(conn): conn.send([42, None, 'hello']) 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()) parent_conn.send("hello child") p.join() # 输出: [42, None, 'hello'] hello child
代码范例3:进程间数据共享
from multiprocessing import Process, Manager import os def f(d, l): d[os.getpid()] = os.getppid() # key:value --> 子进程ID:父进程ID l.append(os.getpid()) print(l) if __name__ == '__main__': with Manager() as manager: #相当于manager = 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)
# 输出: [0, 1, 2, 3, 4, 7460] [0, 1, 2, 3, 4, 7460, 3300] [0, 1, 2, 3, 4, 7460, 3300, 9144] [0, 1, 2, 3, 4, 7460, 3300, 9144, 6172] [0, 1, 2, 3, 4, 7460, 3300, 9144, 6172, 864] [0, 1, 2, 3, 4, 7460, 3300, 9144, 6172, 864, 8008] [0, 1, 2, 3, 4, 7460, 3300, 9144, 6172, 864, 8008, 8128] [0, 1, 2, 3, 4, 7460, 3300, 9144, 6172, 864, 8008, 8128, 9012] [0, 1, 2, 3, 4, 7460, 3300, 9144, 6172, 864, 8008, 8128, 9012, 6428] [0, 1, 2, 3, 4, 7460, 3300, 9144, 6172, 864, 8008, 8128, 9012, 6428, 8196] {864: 6020, 8008: 6020, 3300: 6020, 6428: 6020, 9012: 6020, 9144: 6020, 7460: 6020, 6172: 6020, 8128: 6020, 8196: 6020} [0, 1, 2, 3, 4, 7460, 3300, 9144, 6172, 864, 8008, 8128, 9012, 6428, 8196]
posted on
浙公网安备 33010602011771号