使用工作池写文件
我需要写一些比较大的文件,我想在一个单独的线程中进行这个操作(这样可以同时使用处理器和硬盘)。我打算使用一个大小为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)
1 个回答
3
这是一个受到你原始代码启发的版本。我觉得最重要的变化是函数传递给池的方式(用map
代替了apply_async
,稍后会详细说明):
import os
import multiprocessing
def create_file(e):
with open('files/file%d.txt'%e, 'w') as f:
print f.name
f.write("hi")
if __name__ == '__main__':
if not os.path.exists('files'):
os.makedirs('files')
pool = multiprocessing.Pool(processes=4)
pool.map(create_file, range(10))
你原来的实现有个问题,就是pool.apply_async
会返回一个AsyncResult
对象,而你需要调用get
才能真正开始执行。建议你再仔细看看多进程的文档,特别是关于工作池的这一部分。希望这对你有帮助。