【问题标题】:How to handle out-of-memory error while using threads in python在python中使用线程时如何处理内存不足错误
【发布时间】:2021-08-25 21:32:08
【问题描述】:

我有内存泄漏,但我找不到解决方法。我认为原因是因为我使用线程并且没有以正确的方式停止/杀死它。

我有以下方法:

import threading
def worker():
     if nextJobActive() and number_of_active_threads<5:
         t = threading.Thread(target=startThread, args=(my_list, my_item))
         t.start() 

def startThread(): 
    #do something here, which takes ~15 Min.

我在 while(true) 循环中运行 worker() 方法。在我的情况下,我总是必须启动新线程。但我从不停止线程。我也不知道该怎么做。无论如何,在我的情况下是否可以安全地停止线程?

【问题讨论】:

    标签: python multithreading memory-management memory-leaks out-of-memory


    【解决方案1】:

    如您所知,您正在创建无穷无尽的线程,而没有正确停止前一个线程。要等待线程终止,有一个 .join() 方法。以下是 Thread 模块的文档:docs

    import threading
    def worker():
         if nextJobActive() and number_of_active_threads<5:
             t = threading.Thread(target=startThread, args=(my_list, my_item))
             t.start()
             t.join() 
    
    def startThread(): 
        #do something here, which takes ~15 Min.
    

    【讨论】:

    • 这意味着,新线程将始终启动,旧线程将在其工作完成后终止?
    • 我刚刚测试过;没有加入它总是并行运行 5 个线程,但加入它首先运行 5 个线程,然后只有 1 个线程。有什么想法吗?
    • 一个线程是正在运行的主线程。前五个线程执行,然后它们每个都等待被终止,然后主程序继续作为主线程运行,并且是唯一的线程。如果你打算实现多线程,那么你可以在 threading 模块或 concurrent.futures 模块中使用 lock (docs.python.org/3/library/concurrent.futures.html)
    • 感谢您的回答。在我的情况下,我必须使用线程,用并发替换它会导致很大的开销。如果我在手动完成线程的工作时杀死线程怎么办?或者认为它是否对我有用?
    • 你的主程序就是你的主线程。由于您的主程序永远不会停止调用 return 将无济于事。如果您可以处理所有异常并知道哪些线程完成了它们的工作,那么杀死一个线程应该可以工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-09
    • 2014-07-20
    相关资源
    最近更新 更多