Python pipe.send()挂在Mac操作系统上



如果我在Mac操作系统上返回足够大的字符串,下面的程序总是挂在Mac OS(Python 2.7.5)上。我不能确定限制是多少,但它适用于较小的文本。它在Ubuntu上运行良好,但在pipe_to_parent.send(result)上挂起。

有人知道怎么解决这个问题吗?下面的代码有什么问题吗?

#!/usr/bin/python
import sys
from multiprocessing import Process, Pipe

def run(text, length):
    return (text * ((length / len(text))+1))[:length]
def proc_func(pipe_to_parent):
    result = {'status': 1, 'log': run('Hello World', 20000), 'details': {}, 'exception': ''}
    pipe_to_parent.send(result)
    sys.exit()

def call_run():
    to_child, to_self = Pipe()
    proc = Process(target=proc_func, args=(to_self,))
    proc.start()
    proc.join()
    print(to_child.recv())
    to_child.close()
    to_self.close()
call_run()

文档显示了一个有一些差异的示例,如下所示:

from multiprocessing import Process, Pipe
def f(conn):
    conn.send([42, None, 'hello'])
    conn.close()
if __name__ == '__main__':
    parent_conn, child_conn = Pipe()
    p = Process(target=f, args=(child_conn,))
    p.start()
    # This is the important part
    # Note: conn.recv() is called _before_ process.join()
    print parent_conn.recv()   # prints "[42, None, 'hello']"
    p.join()

在您的示例中,在已经调用process.join()的之后调用.recv()

...
proc = Process(target=proc_func, args=(to_self,))
proc.start()
proc.join()
print(to_child.recv())
...

要想确切了解发生了什么,我们必须查看multiprocessing模块代码,但我猜发生挂起是因为管道试图从封闭端开始读取并阻塞以等待响应。

最新更新