Why can I not create / access futures in callables submitted to ProcessPoolExecutor?

时间:2016-09-18 19:44:28

标签: python python-3.x python-multithreading python-multiprocessing concurrent.futures

Why does this code work with threads but not processes?

import concurrent.futures as f
import time
def wait_on_b():
    time.sleep(2)
    print(b.result())
    return 5

def wait_5():
    time.sleep(2)
    return 6

THREADS = False
if THREADS:
    executor = f.ThreadPoolExecutor()
else:
    executor = f.ProcessPoolExecutor()
a = executor.submit(wait_on_b)
b = executor.submit(wait_5)
print(a.result()) # works fine if THREADS, BrokenProcessPool otherwise

The docs以外的所有子元素警告:

  

从提交给ProcessPoolExecutor的callable调用Executor或Future方法将导致死锁。

文档似乎没有提到引发异常,所以它是否意味着ProcessPoolExecutor以某种方式发现了死锁并通过杀死这两个进程来解决它?

更重要的是,为什么这个死锁对于进程是不可避免的(并且可以通过线程避免),如果我想在未受到限制的情况下使用多个进程和期货,那么解决方法是什么?

1 个答案:

答案 0 :(得分:1)

使用线程时,内存在所有线程之间共享,这就是为什么 wait_on_b 可以访问 b

使用进程,为每个进程创建新内存空间(在fork模式下的副本),这样您将获得 b的副本 PIPE损坏,因为它不是真实 b (只是副本)

顺便说一句:在Windows上有没有分叉,所以 b (内存是全新的)不存在而且你会得到一个

concurrent.futures.process._RemoteTraceback: 
    """
    Traceback (most recent call last):
      File "C:\Anaconda3\lib\concurrent\futures\process.py", line 175, in _process_worker
        r = call_item.fn(*call_item.args, **call_item.kwargs)
      File "C:\Users\yglazner\My Documents\LiClipse Workspace\anaconda_stuff\mproc.py", line 5, in wait_on_b
        print(b.result())
    NameError: name 'b' is not defined
    """