2013-04-08 31 views
1

此問題與previous question I asked有關,它看起來像一個簡單的問題,但我很難找到有關多處理主題的有用信息或教程。聯合輸出多處理python

我的問題是,我想將生成的數據組合成一個大數組,然後將其存儲在我的hdf文件中。

def Simulation(i, output): 
    # make a simulation which outputs it resutlts in A. with shape 4000,3 
    A = np.array([4000,3]) 

    output.put(A) 

def handle_output(output): 
    hdf = pt.openFile('simulation.h5',mode='w') 
    hdf.createGroup('/','data') 

    # Here the output should be joined somehow. 
    # I would like to get it in the shape [4000,3,10] 

    output.get() 
    hdf.createArray('/data','array',A) 
    hdf.close() 

if __name__ == '__main__': 
    output = mp.Queue()  
    jobs = [] 
    proc = mp.Process(target=handle_output, args=(output,)) 
    proc.start() 
    for i in range(10): 
     p = mp.Process(target=Simulation, args=(i, output)) 
     jobs.append(p)  
     p.start() 
    for p in jobs: 
     p.join() 
    output.put(None) 
    proc.join() 

回答

4

你真正需要的是一個多池

就做這樣的事情:

def Simulation(i): 
    return output 

p = mp.Pool(16) 

result = p.map(Simulation,range(10)) 
result = np.array(result).reshape(...) 
p.close() 
p.join() 
+0

簡單有效! – user2143958 2013-04-08 15:09:47