在python中使用线程时如何处理outofmemory错误

2024-09-27 23:16:38 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我有以下方法:

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()方法。在我的情况下,我总是要开始新的线程。但我从不停止一根线。我也不知道怎么做。在我的情况下,是否有任何方法可以安全地停止线程


Tags: and方法内存importifmydef方式
1条回答
网友
1楼 · 发布于 2024-09-27 23:16:38

正如您已经知道的,您正在创建无限多的线程,而没有正确停止前一个线程。要等待线程终止,有一个.join()方法。以下是线程模块的文档: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.

相关问题 更多 >

    热门问题