进程间通讯的三种方式
# 进程间通讯 # 1、进程对列multiprocessing.Quere import multiprocessing, time def foo(q): time.sleep(1) print('son process', id(q)) q.put(123) q.put('alex') if __name__ == '__main__': q = multiprocessing.Queue() print('main process', id(q)) p = multiprocessing.Process(target=foo, args=(q,)) p.start() print(q.get()) print(q.get()) # 2、管道 pipe() from multiprocessing import Process, Pipe def f(conn): conn.send([12, {'name': 'alex'}, 'hello']) response = conn.recv() print('response', response) conn.close() print('q_ID2:', id(conn)) if __name__ == '__main__': parent_conn, child_conn = Pipe() # 双向管道 print('q_ID1:', id(child_conn)) p = Process(target=f, args=(child_conn,)) p.start() print(parent_conn.recv()) parent_conn.send('儿子你好') p.join() # 3、Managers 实现数据共享 (Queue和Pipe只是实现数据交互,没有实现数据共享,即一个进程去更改另一个进程的数据) from multiprocessing import Process, Manager def f(d, l, i): d[i] = '1' # {0: '1'} d['2'] = 2 # {0: '1', '2': 2} l.append(i) # [0, 1, 2, 3, 4, 0] print('son process:', id(d), id(l)) if __name__ == '__main__': with Manager() as manager: d = manager.dict() # 创建Manager字典 {} l = manager.list(range(5)) # 创建Manager列表 [0, 1, 2, 3, 4] print('main process:', id(d), id(l)) p_list = [] for i in range(10): p = Process(target=f, args=(d, l, i)) p.start() p_list.append(p) for res in p_list: res.join() print(d) print(l)