我有6核i5-8600k,并且正在运行Windows 10计算机。我正在尝试使用2 numpy函数执行多重处理。我已经事先发出了一个问题,但是在运行该问题方面并没有取得成功:issue,下面的代码来自该问题的答案。我正在尝试运行func1()
,func2()
但是同时,当我运行下面的代码时,它会永远运行。
import multiprocessing as mp
import numpy as np
num_cores = mp.cpu_count()
Numbers = np.array([1,2,3,4,5,6,7,8,9,10,11,12])
def func1():
Solution_1 = Numbers + 10
return Solution_1
def func2():
Solution_2 = Numbers * 10
return Solution_2
# Getting ready my cores, I left one aside
pool = mp.Pool(num_cores-1)
# This is to use all functions easily
functions = [func1, func2]
# This is to store the results
solutions = []
for function in functions:
solutions.append(pool.apply(function, ()))
代码有几个问题。首先,如果要在Windows的Jupyter Notebook下运行此程序,则需要将辅助函数func1
和func2
外部模块放在例如外部模块中,workers.py
然后导入它们,这意味着您现在需要将Numbers
数组作为参数传递给辅助器或在初始化池时使用数组初始化每个进程的静态存储。我们将为您提供第二种方法,该方法的功能为init_pool
,如果我们在Notebook下运行,则也必须将其导入:
worker.py
def func1():
Solution_1 = Numbers + 10
return Solution_1
def func2():
Solution_2 = Numbers * 10
return Solution_2
def init_pool(n_array):
global Numbers
Numbers = n_array
第二个问题是,在Windows下运行时,创建子流程或多处理池的代码必须位于由conditional控制的块内if __name__ == '__main__':
。第三,如果仅尝试运行两个并行的“作业”,则创建大于2的池大小是浪费的。第四,最后我认为您使用的是错误的合并方法。apply
将阻塞,直到提交的“作业”(即由处理的作业func1
)完成为止,因此您根本无法达到任何程度的并行性。您应该使用apply_async
。
import multiprocessing as mp
import numpy as np
from workers import func1, func2, init_pool
if __name__ == '__main__':
#num_cores = mp.cpu_count()
Numbers = np.array([1,2,3,4,5,6,7,8,9,10,11,12])
pool = mp.Pool(2, initializer=init_pool, initargs=(Numbers,)) # more than 2 is wasteful
# This is to use all functions easily
functions = [func1, func2]
# This is to store the results
solutions = []
results = [pool.apply_async(function) for function in functions]
for result in results:
solutions.append(result.get()) # wait for completion and get the result
print(solutions)
印刷:
[array([11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]), array([ 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120])]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句