python3 Timer 内存泄漏

发现我如下使用Timer会出现内存泄漏,程序运行起来,内存使用量快速增加,不会减少。这段代码在tkinter界面中,若用tkinter.after将Timer替换,内存泄漏就不存在了。如何使用Timer才是正确的姿势?谢谢!

from threading import Timer, Thread
from queue import Queue
import time

def opWork():
    while True:
        if not opQueue.empty():
            opQueue.get()
            print(" -------------- pocess a cmd!")
        else:
            time.sleep(0.001)

def tickOff():
    opQueue.put("cmd")
    global tick
    tick.cancel()
    tick = Timer(0.001, tickOff)      
    tick.start()
    print("add a cmd! -------------- ")

tick = Timer(0.001, tickOff)  

if __name__ == "__main__":
    opQueue = Queue()

    worker = Thread(target=opWork)
    worker.start()

    tick.start()


是python本身的bug吗?刚找到这个 [issue43050] threading timer memory leak

问题代码如下:

While True:
    timer = threading.Timer(5, None)
    timer.start()
    timer.cancel()

我试了,内存快速增加,不会减少。

阅读 4.1k
1 个回答
def tickOff():
    opQueue.put("cmd")
    global tick
    tick.cancel()
    tick = Timer(0.001, tickOff)      
    tick.start()
    print("add a cmd! -------------- ")

tick = Timer(0.001, tickOff) 自己在调自己 无限递归

from threading import Timer, Thread
from queue import Queue
import time

def opWork():
    while True:
        if not opQueue.empty():
            opQueue.get()
            print(" -------------- pocess a cmd!")
        else:
            time.sleep(0.001)

def tickOff():
    opQueue.put("cmd")

if __name__ == "__main__":
    opQueue = Queue()

    worker = Thread(target=opWork)
    worker.start()

    while 1:
      tickOff()
      time.sleep(1)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题