標籤:管道
multiprocessing.Pipe([duplex])
返回2個連線物件(conn1, conn2),代表管道的兩端,預設是雙向通訊.如果duplex=False,conn1隻能用來接收訊息,conn2隻能用來發送訊息.不同於os.open之處在於os.pipe()返回2個檔案描述符(r, w),表示可讀的和可寫的
執行個體如下:
#!/usr/bin/python
#coding=utf-8
import os
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()
print "con2 got: %s" % con2.recv()#從send收到訊息
con2.close()
(parentEnd, childEnd) = Pipe()
child = Process(target = talk, name = ‘talk‘, args = (childEnd,))
child.start()
print(‘parent got:‘, parentEnd.recv())
parentEnd.send({x * 2 for x in ‘spam‘})
child.join()
print(‘parent exit‘)
輸出如下:
con2 got: [‘spam‘, 42, ‘egg‘]
(‘parent got:‘, {‘name‘: ‘Bob‘, ‘spam‘: 42})
(‘talker got:‘, set([‘ss‘, ‘aa‘, ‘pp‘, ‘mm‘]))
parent exit
codego.net代碼節選.
Python multiprocessing模組中的Pipe管道