是否可以在进程之间传递 Python Future 对象?

Is it possible to pass Python Future objects between processes?

根据我的实验,我猜答案是否定的。但也许可以通过对期货模块进行一些更改来实现。

我想提交一个worker,它自己创建一个executor并提交工作。我想 return 主进程的第二个未来。我有这个 MWE,它不起作用,因为 f2 对象在通过多处理发送时可能与其父执行器断开关联。 (如果两个执行器都是 ThreadPoolExecutor,它确实有效,因为永远不会复制 f2 对象)。

from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
import time

def job1():
    try:
        ex2 = ThreadPoolExecutor()
        time.sleep(2)
        f2 = ex2.submit(job2)
    finally:
        ex2.shutdown(wait=False)
    return f2

def job2():
    time.sleep(2)
    return 'done'

try:
    ex1 = ProcessPoolExecutor()
    f1 = ex1.submit(job1)
finally:
    ex1.shutdown(wait=False)

print('f1 = {!r}'.format(f1))
f2 = f1.result()
print('f1 = {!r}'.format(f1))
print('f2 = {!r}'.format(f2))

我的问题是:有没有什么安全的方法可以让我通过多处理管道发送一个未来的对象,并能够在它完成时接收到该值。看来我可能需要设置另一个类似执行程序的构造来侦听另一个管道上的结果。

我当前的设置是 Ubuntu 16.04.5 LTS 和 Python 3.6.5。当 运行 上面发布的代码时,我收到以下错误:

f2 = f1.result()

其次是

concurrent.futures.process.BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending.

翻阅Python文档,发现在17.4.3下。 ProcessPoolExecutor

"calling Executor or Future methods from a callable submitted to a ProcessPoolExecutor will result in deadlock."

此外,在

class concurrent.futures.ProcessPoolExecutor(max_workers=None)

我还发现了以下内容:

"changed in version 3.3: when one of the worker processes terminates abruptly, a BrokenProcessPool error is now raised. Previously, behaviour was undefined but operations on the executor or its futures would often freeze or deadlock."

此外,根据定义,ProcessPoolExecutor 会关闭全局解释器锁,打开它以供其他进程访问。

要回答关于是否有任何安全方法可用于通过多处理管道发送未来对象并在另一端接收它的问题,我会拒绝标准库。

参考文献:

https://docs.python.org/3.6/library/concurrent.futures.html#processpoolexecutor

https://docs.python.org/3.6/glossary.html#term-global-interpreter-lock