Skip to main content
 首页 » 编程设计

具有共享数据的 Python 多处理池

2025年04月02日8arxive

我正在尝试使用多处理来加速多元定点迭代算法,但是,我在处理共享数据时遇到了问题。我的解决方案向量实际上是一个命名字典而不是数字向量。向量的每个元素实际上是使用不同的公式计算的。在高层次上,我有一个这样的算法:

current_estimate = previous_estimate 
while True: 
for state in all_states: 
    current_estimate[state] = state.getValue(previous_estimate) 
if norm(current_estimate, previous_estimate) < tolerance: 
    break 
else: 
    previous_estimate, current_estimate = current_estimate, previous_estimate 

我正在尝试将 for 循环部分与多处理并行化。 previous_estimate 变量是只读的,每个进程只需要写入 current_estimate 的一个元素。我目前重写 for 循环的尝试如下:

# Class and function definitions 
class A(object): 
    def __init__(self,val): 
        self.val = val 
 
    # representative getValue function 
    def getValue(self, est): 
        return est[self] + self.val 
 
def worker(state, in_est, out_est): 
    out_est[state] = state.getValue(in_est) 
 
def worker_star(a_b_c): 
    """ Allow multiple arguments for a pool 
        Taken from http://stackoverflow.com/a/5443941/3865495 
    """ 
    return worker(*a_b_c) 
 
# Initialize test environment 
manager = Manager() 
estimates = manager.dict() 
all_states = [] 
for i in range(5): 
     a = A(i) 
     all_states.append(a) 
     estimates[a] = 0 
 
pool = Pool(process = 2) 
prev_est = estimates 
curr_est = estimates 
pool.map(worker_star, itertools.izip(all_states, itertools.repeat(prev_est), itertools.repreat(curr_est))) 

我目前遇到的问题是添加到 all_states 数组的元素与添加到 manager.dict() 的元素不同。尝试使用数组元素访问字典元素时,我不断收到 key value 错误。并且调试,发现没有一个元素是一样的。

print map(id, estimates.keys()) 
>>> [19558864, 19558928, 19558992, 19559056, 19559120] 
print map(id, all_states) 
>>> [19416144, 19416208, 19416272, 19416336, 19416400] 

请您参考如下方法:

发生这种情况是因为您放入 estimates DictProxy 的对象实际上与常规字典中的对象不同。 manager.dict() 调用返回一个 DictProxy,它代理对实际上位于完全独立的管理器进程中的 dict 的访问。当您将东西插入其中时,它们实际上被复制并发送到远程进程,这意味着它们将具有不同的身份。

要解决此问题,您可以在 A 上定义自己的 __eq__ 和 __hash__ 函数,如 described in this question :

class A(object): 
    def __init__(self,val): 
        self.val = val 
 
    # representative getValue function 
    def getValue(self, est): 
        return est[self] + self.val 
 
    def __hash__(self): 
        return hash(self.__key()) 
 
    def __key(self): 
        return (self.val,) 
 
    def __eq__(x, y): 
        return x.__key() == y.__key() 

这意味着 estimates 中项目的键查找将只使用 val 属性的值来确定身份和相等性,而不是 id 由 Python 赋值。