python 进程间通信_python进程间通信之Pipe

熟悉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 --

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值