通过pipe 管道的方式也可以实现进程间通信。
父进程和子进程之间可以实现相互通信。
from multiprocessing import Process, Pipe def f(conn): conn.send([42, None, 'hello from child']) conn.send([42, None, 'hello from child2']) print('from parent:',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()) # prints "[42, None, 'hello']" print(parent_conn.recv()) parent_conn.send('你还好么?') p.join()
运行结果:
[42, None, 'hello from child'] [42, None, 'hello from child2'] from parent 你还好么?