【发布时间】:2016-02-06 00:37:01
【问题描述】:
如标题所示,我在使用multiprocessing 时遇到了内存泄漏问题。我知道以前有人问过这样的问题,但我仍然找不到适合我的问题的解决方案。
我有一个 RGB 图像列表(30.000 总计)。我需要读取每张图像,处理所有三个 RGB 通道,然后将结果保存在内存中(稍后保存在1 大文件中)
我正在尝试使用这样的东西:
import multiprocessing as mp
import random
import numpy as np
# Define an output queue to store result
output = mp.Queue()
# define a example function
def read_and_process_image(id, output):
result = np.random.randint(256, size=(100, 100, 3)) #fake an image
output.put(result)
# Setup a list of processes that we want to run
processes = [mp.Process(target=read_and_process_image, args=(id, output)) for id in range(30000)]
# Run processes
for p in processes:
p.start()
# # Exit the completed processes
# for p in processes:
# p.join()
# Get process results from the output queue
results = [output.get() for p in processes]
print(results)
此代码使用大量内存。 This answer 解释了这个问题,但我找不到将它应用到我的代码的方法。有什么建议吗?谢谢!
编辑:我也尝试joblib 和Pool 类,但代码不会像我预期的那样使用所有内核(我认为使用普通for 循环没有区别有这两种情况)
【问题讨论】:
-
您不想启动 30000 个进程。使用池来限制生成的进程数。
-
如何使用pool来限制进程数(但使用我CPU的所有核心)?我试过了,但代码并没有按照我的意愿使用所有的 CPU。 @ReutSharabani
标签: python memory-leaks threadpool python-multiprocessing