multiprocessing.Pipe()用来创建管道,返回两个连接对象,代表管道的两端,一般用于进程或者线程之间的通信,不同于os.pipe(),os.pipe()主要用来创建两个文件描述符,一个读,一个写,是单向的。而multiprocessing.Pipe()则可以双向通信。
from multiprocessing import Process, Pipe
def send(pipe):
pipe.send(['spam'] + [42, 'egg'])
pipe.close()
def talk(pipe):
pipe.send(dict(name = 'Bob', spam = 42))
reply = pipe.recv()
print('talker got:', reply)
if __name__ == '__main__':
(con1, con2) = Pipe()
sender = Process(target = send, name = 'send', args = (con1, ))
sender.start()
child = Process(target = talk, name = 'talk', args = (con2,))
child.start()
结果:
('talker got:', ['spam', 42, 'egg'])