我必须写一些相当大的文件,我想在一个单独的线程(同时使用处理器和硬盘驱动器)和我想使用一个大小为4的工人池(因为除了写,还有其他操作,我想4足够正常使用硬盘驱动器,而不堵塞它)。在
这是我的代码(它什么也不做):
import os, os.path, multiprocessing
def asyncFileMake(e):
with open('files/file%d.txt'%e, 'w') as f:
print(os.path.dirname(os.path.abspath(os.getcwd())))
f.write("hi")
def writefile(e, pool):
pool.apply_async(asyncFileMake, [e])
if __name__ == "__main__":
if not os.path.exists('files'):
os.makedirs('files')
with multiprocessing.Pool(processes=4) as pool:
for e in range(10):
writefile(e, pool)
这里有一个版本,它的灵感来自于您的原始代码片段。我认为最重要的变化是函数传递到池的方式(},稍后将详细介绍):
map
而不是{原始实现的问题是,
pool.apply_async
返回一个AsyncResult
,您需要调用get
以便触发实际执行。我建议你再仔细看看documentation of multiprocessing。尤其是this part about pool workers。希望有帮助。在相关问题 更多 >
编程相关推荐