python3 Timer 内存泄漏

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()

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


回答:

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)

以上是 python3 Timer 内存泄漏 的全部内容, 来源链接: utcz.com/p/937989.html

回到顶部