所有示例concurrent.futures代码都失败了"BrokenProcessPool"

Gar*_*ber 15 python python-3.x

在创建我需要的实际应用程序之前,我试图对此有一个基本的了解.我最近从2.7移到了3.3.

从python文档直接复制粘贴此代码失败,这里稍微简单的示例也是如此.

这是我的代码,派生自第二个例子:

import concurrent.futures

nums = [1,2,3,4,5,6,7,8,9,10]

def f(x):
    return x * x

# Make sure the map and function are working
print([val for val in map(f, nums)])

# Test to make sure concurrent map is working
with concurrent.futures.ProcessPoolExecutor() as executor:
    for item in executor.map(f, nums):
        print(item)
Run Code Online (Sandbox Code Playgroud)

这是输出:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Traceback (most recent call last):
  File "<string>", line 420, in run_nodebug
  File "<module1>", line 13, in <module>
  File "C:\Python33\lib\concurrent\futures\_base.py", line 546, in result_iterator
    yield future.result()
  File "C:\Python33\lib\concurrent\futures\_base.py", line 399, in result
    return self.__get_result()
  File "C:\Python33\lib\concurrent\futures\_base.py", line 351, in __get_result
    raise self._exception
concurrent.futures.process.BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending.
Run Code Online (Sandbox Code Playgroud)

如何让这段代码按预期工作?我希望这些例子能够开箱即用.

Gar*_*ber 20

这是我的错,原因有两个:

  1. 代码没有防范,即没有 if __name__
  2. 奇怪的Traceback是因为文件没有保存.从来没有给我带来过问题,但在这种情况下做了.

纠正那两个修复错误.

最终测试代码:

import concurrent.futures

nums = [1,2,3,4,5,6,7,8,9,10]

def f(x):
    return x * x
def main():
    # Make sure the map and function are working
    print([val for val in map(f, nums)])

    # Test to make sure concurrent map is working
    with concurrent.futures.ProcessPoolExecutor() as executor:
        print([val for val in executor.map(f, nums)])

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

输出,如预期:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Run Code Online (Sandbox Code Playgroud)

  • @David现在在[ProcessPoolExecutor的文档](https://docs.python.org/3/library/concurrent.futures.html)中提到它在交互式控制台中不起作用。它说* __ main__模块必须可由工作程序子进程导入。这意味着ProcessPoolExecutor将无法在交互式解释器中工作。* (3认同)
  • 真奇怪 它仅对保存的.py文件有效。当我在iPython控制台或Jupyter笔记本中尝试时,它失败了。好发现! (2认同)
  • 我的另一个发现是,当您尝试在 Windows 内执行进程池时,会出现该消息。在Linux下执行时,运行良好。 (2认同)

小智 6

在Windows下,保护代码的主循环非常重要,以避免在使用processpoolexecutor或产生新进程的任何其他并行代码时递归生成子进程.

基本上,创建新进程的所有代码都必须在if __name__ == '__main__':,因为您无法在解释器中执行它.