python - 结合输出多处理python

标签 python multiprocessing

此问题与 previous question I asked 有关,这似乎是一个简单的问题,但我很难找到有关多处理主题的有用信息或教程。

我的问题是我想将生成的数据组合成一个大数组,然后将其存储在我的 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()

最佳答案

你真正需要的是一个多处理池

只需执行以下操作:

def Simulation(i): 
    return output

p = mp.Pool(16)

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

关于python - 结合输出多处理python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15881055/

相关文章:

python - 在输入时保持 Visual Studio (Python) 中的当前缩进?

python - 哪个Python图形库可以移动点

python - 使用多处理时无法 pickle 静态方法

python - 多处理 : use tqdm to display a progress bar

python - 从Python中的字典中提取键和值(以线程安全的方式)

python - 在 python 中重写 __import__

python - 如何使用 pd.Timestamp 函数将数据列更改为时间戳格式

python - 在 C++ 中使用 python obj 与 pybind 和 multiprocessing.Process

python - multiprocessing.Connect 线程安全吗?

当我们运行许多任务时,python 多处理池不起作用