Python多处理管道将无法正确recv() [英] Python multiprocessing pipe will not recv() properly

查看:208
本文介绍了Python多处理管道将无法正确recv()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是针对Python 3.2.2.我只是在学习Python和多处理的工作方式,这个简单的例子让我很困惑:

This is for Python 3.2.2. I'm only just learning how Python and multiprocessing work and this simple example has been tripping me:

from multiprocessing import Pipe, Process

def f(r):
    print(r.recv())

if __name__ == '__main__':
    q, r = Pipe()
    p = Process(target=f, args=(r,))
    p.start()
    q.send([42, None, 'hello'])
    p.join()

主线程创建一个新的Processp,并将双向连接对象r发送给功能f().当进程p启动时,我希望r.recv()阻塞(据我所知,这意味着该进程将无限期等待,直到有东西通过管道为止),直到主进程通过q.send发送一些对象为止

The main thread creates a new Process, p, and sends r, a bidirectional connection object, to function f(). When process p is started, I expect r.recv() to block (which, as far as I understand, means that this process will wait indefinitely until something comes through the pipe) until the main process sends some objects through with q.send.

然后p.join()应该使主进程等待,直到p运行完毕.

Then p.join() should make the main process wait until p has run its course.

但是什么也没发生.如果在f()上添加print语句,也不会发生任何事情,就像f()从未运行过并且p.start()无法正常工作一样.

But nothing whatsoever happens. If I add a print statement to f(), nothing happens there, either, as if f() never even runs and p.start() is nonfunctional.

您能解释一下为什么这种方法不起作用以及可能解决的问题吗?

Can you explain why this won't work and what might be fixed?

推荐答案

我知道已经有一段时间了,但是对于其他有此问题的人来说,您的管道末端已经颠倒了.您正在尝试使用接收端进行发送,并尝试通过发送端进行接收.我发现在Pipe构造函数中添加duplex = True可以更轻松地处理不同的目标.

I know it's been a while, but for others with this problem, you have the ends of your pipe reversed. You're trying to use the receiving end to send, and trying to receive with the sending end. I find that adding duplex=True to the Pipe constructor makes it much easier to deal with the different ends.

来源: https://docs.python.org/2/library/multiprocessing.html#pipes-and-queues

这篇关于Python多处理管道将无法正确recv()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆