multiprocessing.Pipe()的用法

来源:互联网 发布:java多线程视频教程 编辑:程序博客网 时间:2024/06/04 20:01

multiprocessing.Pipe()用来创建管道,返回两个连接对象,代表管道的两端,一般用于进程或者线程之间的通信,不同于os.pipe(),os.pipe()主要用来创建两个文件描述符,一个读,一个写,是单向的。而multiprocessing.Pipe()则可以双向通信。

from multiprocessing import Process, Pipedef 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'])

1 0
原创粉丝点击