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
这是我的错,原因有两个:
if __name__纠正那两个修复错误.
最终测试代码:
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)
小智 6
在Windows下,保护代码的主循环非常重要,以避免在使用processpoolexecutor或产生新进程的任何其他并行代码时递归生成子进程.
基本上,创建新进程的所有代码都必须在if __name__ == '__main__':,因为您无法在解释器中执行它.
| 归档时间: |
|
| 查看次数: |
13551 次 |
| 最近记录: |