在不停止池多处理的情况下对共享阵列进行平等测试

时间:2019-08-08 08:21:02

标签: python numpy multiprocessing

我正在使用multiprocessing python库,可以使用它在共享数组上并行化内部循环。 我正在使用Python3和具有多个CPU的Linux计算机。

此内部循环必须重复一定次数,直到此数组停止更改为止。

我正在做的是停止池以与共享阵列的最后状态进行比较,然后如果阵列发生更改,则重新启动池。 我认为不断停止并重新启动池会产生成本。它有效,但是有办法更有效地做到吗? (list_of_args完全没有改变)

import multiprocessing as mp
from multiprocessing import Pool
import numpy as np
shared_arr = mp.Array("i", np.arange(N), lock=False)
#Can only be performed if the pool is stopped
current_state = np.array(shared_arr)
def init_globals(array_args):
    global shared_arr
    shared_arr = array_args

while True:
        # Starting the pool
        with Pool(initializer=init_globals, initargs=(shared_arr,)) as pool:
            pool.starmap(f, list_of_args)
        # Exiting context manager therefore stopping the pool
        next_state = np.array(sharred_ar)
        if np.array_equal(next_state, current_state):
            break
        else:
            current_state = next_state

可能以有效的代码with Pool可以放置在while循环之外。有办法吗?

0 个答案:

没有答案