首页 > 解决方案 > Python 线程 - 内存未释放

问题描述

我需要为用户请求调用生成一个作业 ID,我想使用以下块通过python-theading处理它:

from flask_restful import Resource
from flask import copy_current_request_context
import uuid
import time
class ScoreReportGenerator:
    def trigger_job():
        try:
            # Do memory-intensive process
            return "success"
        except:
            return "failure"

class JobSubmitter(Resource):
    def post(self):
        job_id = uuid.uuid4()

        @copy_current_request_context
        def start_score_report_generator_thread(payload_data, job_id):
            score_report_generator = ScoreReportGenerator()
            score_report_generator.trigger_job()

        t = threading.Thread(target=start_score_report_generator_thread, args=[payload_data, job_id])
        t.setDaemon(False)
        t.start()
        
        response = dict()
        response["status"] = "RUNNING"
        response["jobId"] = str(job_id)
        return response

这里已经注意到,这个生成的线程占用了大约 70GB 的 RAM,在线程完成后 70GB 的 RAM 仍然被占用。杀死整个 python 应用程序后,RAM 被释放。

期待释放RAM-Memory消耗的建议,欢迎任何帮助!

提前致谢!

标签: pythonmultithreadingflaskpython-multithreadingflask-restful

解决方案


可能为您解决问题的解决方案是使用垃圾收集器并启用它。

import gc
gc.enable()

并检查自动垃圾收集解决方案是否能解决您的问题。如果它不检查详细信息,是否有手动程序可以为您完成。

https://docs.python.org/3/library/gc.html


推荐阅读