如果我在 Mac OS 上返回足够大的字符串,以下程序总是在 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()
请您参考如下方法:
documentation显示了一个有一些差异的示例,如下所示:
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()
在您的示例中,您调用 .recv() 之后您已经调用了 process.join()。
...
proc = Process(target=proc_func, args=(to_self,))
proc.start()
proc.join()
print(to_child.recv())
...
要准确了解发生了什么,我们必须查看 multiprocessing 模块代码,但我猜测挂起是因为管道正试图从一个已关闭的进程开始读取结束并阻塞以等待响应。
