我有一个简单但非常耗时的功能,我想对其进行并行化以使其更快。这是Jupyter Notebook上的Python 3.6。我做这样的事情:
from multiprocessing import Pool
def func(x):
return x**2
y = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
with Pool(5) as pool:
results = pool.imap_unordered(func, y)
for r in results:
print(r)
最后一条语句永远运行,永远不会结束。
这是怎么了?
答案 0 :(得分:0)
您遇到了上下文范围问题。尝试在for r in results:
块内移动with
循环:
with Pool(5) as pool:
results = pool.imap_unordered(func, y)
for r in results:
print(r)
这很好。
或者,您可以只使用Pool.map
from multiprocessing import Pool
def func(x):
return x ** 2
if __name__ == '__main__':
y = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
with Pool(5) as pool:
results = pool.map(func, y)
for r in results:
print(r)
可打印
1
4
9
16
25
36
49
64
81
100