【发布时间】:2016-04-18 15:11:10
【问题描述】:
我正在做一些文件解析,这是一个 CPU 密集型任务。无论我在这个过程中扔了多少文件,它使用的 RAM 都不超过 50MB。 该任务是可并行的,我已将其设置为使用下面的并发期货将每个文件解析为单独的进程:
from concurrent import futures
with futures.ProcessPoolExecutor(max_workers=6) as executor:
# A dictionary which will contain a list the future info in the key, and the filename in the value
jobs = {}
# Loop through the files, and run the parse function for each file, sending the file-name to it.
# The results of can come back in any order.
for this_file in files_list:
job = executor.submit(parse_function, this_file, **parser_variables)
jobs[job] = this_file
# Get the completed jobs whenever they are done
for job in futures.as_completed(jobs):
# Send the result of the file the job is based on (jobs[job]) and the job (job.result)
results_list = job.result()
this_file = jobs[job]
# delete the result from the dict as we don't need to store it.
del jobs[job]
# post-processing (putting the results into a database)
post_process(this_file, results_list)
问题是,当我使用期货运行它时,RAM 使用量猛增,不久我就用完了,Python 崩溃了。这可能在很大程度上是因为 parse_function 的结果大小为几 MB。一旦结果通过post_processing,应用程序就不再需要它们。如您所见,我正在尝试del jobs[job] 从jobs 中清除项目,但这没有任何区别,内存使用量保持不变,并且似乎以相同的速度增加。
我还确认这不是因为它仅使用单个进程在等待post_process 函数,并抛出time.sleep(1)。
futures 文档中没有关于内存管理的任何内容,虽然简短的搜索表明它之前已经出现在 future 的实际应用中(Clear memory in python loop 和 http://grokbase.com/t/python/python-list/1458ss5etz/real-world-use-of-concurrent-futures) - 答案并没有转化为我的使用-case(他们都关心超时等)。
那么,如何在不耗尽 RAM 的情况下使用并发期货? (Python 3.5)
【问题讨论】:
标签: python python-3.x memory-management parallel-processing