首页 > 解决方案 > 在不停止池多处理的情况下对共享阵列进行平等测试

问题描述

我正在使用multiprocessingpython 库,可以使用它来并行化共享数组上的内部循环。我正在使用 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循环之外。有没有办法做到这一点 ?

标签: pythonnumpymultiprocessing

解决方案


推荐阅读