熟悉Linux系统的同学,都应该很熟悉pipe,我们再shell命令行上常常使用,用来在多个进程之间传递信息。python也有通过Pipe来再进程间通信的机制,不过这个代码中的Pipe,在使用上,更像socket。
相对于multiprocess.Queue,pipe更快,但是不适合多个进程间的通信。
from multiprocessing import Process, Pipe
def f(conn):
conn.send([42, None, 'hello'])
for i in range(2):
print(conn.recv())
if __name__ == '__main__':
parent_conn, child_conn = Pipe()
p = Process(target=f, args=(child_conn,))
p.start()
print(parent_conn.recv())
parent_conn.send('i am your father!!')
parent_conn.send('boy...')
p.join()
多进程通信的Pipe管道构建的时候返回两个对象,这两个对象之间可以通过send和recv方法传递数据。
The two connection objects returned by Pipe() represent the two ends of the pipe. Each connection object has send() and recv() methods (among others). Note that data in a pipe may become corrupted if two processes (or threads) try to read from or write to the same end of the pipe at the same time. Of course there is no risk of corruption from processes using different ends of the pipe at the same time.
多个线程同时访问Pipe的一端的时候,需要互斥!
multiprocessing.Pipe([duplex])
Returns a pair (conn1, conn2) of Connection objects representing the ends of a pipe.
If duplex is True (the default) then the pipe is bidirectional. If duplex is False then the pipe is unidirectional: conn1 can only be used for receiving messages and conn2 can only be used for sending messages.
Pipe默认是双向的,也可以用duplex=False来创建单向的Pipe,这就更像我们在shell命令行上使用的pipe了。
-- EOF --