2017-04-16 89 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)