每次以 write ( w
) 模式打开文件时,都会创建一个新文件——因此如果文件已经存在,则文件的内容会丢失。只有最后一个文件句柄才能成功写入文件。即使您将其更改为附加模式,您也不应该尝试从多个进程写入同一个文件——如果两个进程同时尝试写入,输出将会出现乱码。
相反,让所有工作进程将输出放入队列中,并让一个专用进程(子进程或主进程)处理队列的输出并写入文件:
import multiprocessing as mp
import tables as pt
num_arrays = 100
num_processes = mp.cpu_count()
num_simulations = 1000
sentinel = None
def Simulation(inqueue, output):
for ii in iter(inqueue.get, sentinel):
output.put(('createGroup', ('/', 'A%s' % ii)))
for i in range(num_arrays):
output.put(('createArray', ('/A%s' % ii, 'B%s' % i, [ii, i])))
def handle_output(output):
hdf = pt.openFile('simulation.h5', mode='w')
while True:
args = output.get()
if args:
method, args = args
getattr(hdf, method)(*args)
else:
break
hdf.close()
if __name__ == '__main__':
output = mp.Queue()
inqueue = mp.Queue()
jobs = []
proc = mp.Process(target=handle_output, args=(output, ))
proc.start()
for i in range(num_processes):
p = mp.Process(target=Simulation, args=(inqueue, output))
jobs.append(p)
p.start()
for i in range(num_simulations):
inqueue.put(i)
for i in range(num_processes):
# Send the sentinal to tell Simulation to end
inqueue.put(sentinel)
for p in jobs:
p.join()
output.put(None)
proc.join()
为了比较,这是一个使用的版本mp.Pool
:
import multiprocessing as mp
import tables as pt
num_arrays = 100
num_processes = mp.cpu_count()
num_simulations = 1000
def Simulation(ii):
result = []
result.append(('createGroup', ('/', 'A%s' % ii)))
for i in range(num_arrays):
result.append(('createArray', ('/A%s' % ii, 'B%s' % i, [ii, i])))
return result
def handle_output(result):
hdf = pt.openFile('simulation.h5', mode='a')
for args in result:
method, args = args
getattr(hdf, method)(*args)
hdf.close()
if __name__ == '__main__':
# clear the file
hdf = pt.openFile('simulation.h5', mode='w')
hdf.close()
pool = mp.Pool(num_processes)
for i in range(num_simulations):
pool.apply_async(Simulation, (i, ), callback=handle_output)
pool.close()
pool.join()
它看起来更简单不是吗?然而,有一个显着的区别。output.put
用于发送 args的原始代码handle_output
在其自己的子进程中运行。handle_output
将从队列中取出并立即处理它们args
。output
使用上面的 Pool 代码,Simulation
累积一大堆args
inresult
并且直到返回后才result
发送到。handle_output
Simulation
如果Simulation
需要很长时间,则将有很长的等待时间,而没有写入任何内容simulation.h5
。