2017-04-16 61 views
0

问题共享阵列:访问来自多个处理器的

我要访问所有进程在y共享变量,因为在new_y每个元素我想使它成为当前y和下一ÿ 像new_y [i] = y [i] + y [i + 1]。我如何获取当前池工作人员对我发送的数组y的索引?

import multiprocessing 

num_processes = 2 
y = multiprocessing.Array('d', 6, lock=False) 
new_y = multiprocessing.Array('d', 6, lock=False) 

def init_process(y_to_share, new_y_to_share): 
    global y, new_y 
    y = y_to_share 
    new_y = new_y_to_share 

process_pool = multiprocessing.Pool(
        num_processes, 
        initializer=init_process, 
        initargs=(y, new_y)) 

dt = 0.0001 
def sq(): 
    global y 
    global new_y 
    print new_y[0] 
    print multiprocessing.current_process() 
    #Here I want to do y at the current index and add the y value of the next index 
    #something like new_y[i] = y[i]+y[i+1] 


process_pool.map(sq, y) 
+0

当'multiprocessing'说“共享”,它确实意味着每个进程都有自己的副本在代理对象,并有后台的协议尝试保持全部同步。我发现它几乎毫无意义。 – tdelaney

+0

@tdelaney这很好,但让我们只是说我想访问该数组中我正在处理的元素旁边的元素。例如在迭代中,我得到了一个x的值,我想使用x和x旁边数组中的值如何访问共享数组中的值?基本上我需要地图传入的x值的位置。 – Kevin

+0

你可以用'枚举'来完成它,但好像你根本不需要共享'new_y'。你的地图可能是'pool.map(sq,(y [i:i + 2]),我在范围内(len(y)-1))'。 – tdelaney

回答

1

我犹豫回答,因为我可能是完全误解了问题,但你可以改变你迭代的父进程是什么使得它有你想要的相邻数据处理这个。

import multiprocessing 

def worker(yvals): 
    return yvals[0] + yvals[1] 

if __name__ == "__main__": 
    y_list = list(range(6)) 
    pool = multiprocessing.Pool() 
    new_y = list(pool.map(worker, 
     (y_list[i:i+2] for i in range(len(y_list)-1)))) 
    pool.close() 
    print(new_y) 

在linux上,当一个池启动时,它有一个父地址空间的写时复制视图,并且可以只读该列表。我不确定在这种情况下Windows会发生什么,但它试图腌制父环境并用它初始化孩子 - 让我想知道为什么有人会在Windows上使用这个模块! - 但对于linux和OSX至少,这将工作

import multiprocessing 

def worker(y_index): 
    return y_list[y_index] + y_list[y_index+1] 

if __name__ == "__main__": 
    y_list = list(range(6)) 
    pool = multiprocessing.Pool() 
    new_y = list(pool.map(worker, range(len(y_list)-1))) 
    print(new_y) 
相关问题