gpt4 book ai didi

python - 所有示例 concurrent.futures 代码都失败并显示 "BrokenProcessPool"

转载 作者:太空狗 更新时间:2023-10-29 17:14:41 36 4
gpt4 key购买 nike

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

this code from the python docs 的直接复制粘贴失败,来自 here 的一个稍微简单的例子也是如此.

这是我的代码,源自第二个示例:

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)

这是输出:

[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.

如何让这段代码按预期工作?我希望这些示例开箱即用。

最佳答案

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

  1. 代码未 protected ,即没有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()

输出,如预期:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

关于python - 所有示例 concurrent.futures 代码都失败并显示 "BrokenProcessPool",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15900366/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com