[英]Python 2.7, thread.Timer generates too many garbage threads not recycled
我在Windows上运行python示例代码,每次执行计时器线程后,都会创建一个如下所示的新线程,但是旧线程永远不会回收,这确实使线程数量不断增加,这恐怕使我的软件望而却步不久或以后都会消耗整个PC内存。 我看到许多其他人也遇到了相同的问题,当使用pydev进行调试时,最终将报告“ TclError:out of stack space ”!
这是我的pydev调试堆栈的列表,它将不断增加,直到“堆栈空间不足”为止,从堆栈视图中,我看到线程数量非常疯狂……
Thread-1913 - pid_9200_id_155817632
Thread-1915 - pid_9200_id_156052840
Thread-1917 - pid_9200_id_156052112
Thread-1919 - pid_9200_id_156326208
Thread-1921 - pid_9200_id_156326264
pydev报告的错误如下:
pydev debugger: starting (pid: 9200)
Exception in thread Thread-1921:
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 801, in __bootstrap_inner
self.run()
File "C:\Python27\lib\threading.py", line 1073, in run
self.function(*self.args, **self.kwargs)
File "D:\work\tools\eclipseWorkspace\timerTest.py", line 46, in handle_function
self.hFunction()
File "D:\work\tools\eclipseWorkspace\timerTest.py", line 56, in printer
lab['text'] = clock
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1337, in __setitem__
self.configure({key: value})
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1330, in configure
return self._configure('configure', cnf, kw)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1321, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
TclError: out of stack space (infinite loop?)
下面是我的代码,它设置一个计时器,然后调用函数“ loop”
from threading import Timer, Thread, Event
from datetime import datetime
import Tkinter as tk
app = tk.Tk()
lab = tk.Label(app, text="Timer will start in a sec")
lab.pack()
class perpetualTimer():
def __init__(self, t, hFunction):
self.t = t
self.hFunction = hFunction
self.thread = Timer(self.t, self.loop)
def loop(self):
self.hFunction()
self.thread = Timer(self.t, self.loop)
self.thread.start()
def start(self):
self.thread.start()
def printer():
tempo = datetime.today()
clock = "{}:{}:{}".format(tempo.hour, tempo.minute, tempo.second)
try:
lab['text'] = clock
except RuntimeError:
exit()
t = perpetualTimer(0.1, printer)
t.start()
app.mainloop()
您的代码无法在我的Python上执行。 触发计时器线程后,无需取消它。 换一个新的。 另外,将第一次创建的Timer放在初始化例程中,然后等待它执行处理功能会更清洁:
class perpetualTimer():
def __init__(self, t, hFunction):
self.t = t
self.hFunction = hFunction
self.thread = Timer(self.t, self.handle_function)
def handle_function(self):
self.hFunction()
self.thread = Timer(self.t, self.handle_function)
self.thread.start()
def start(self):
self.thread.start()
所有Timer线程在触发后终止,以后将被垃圾回收。 它们不会填充所有可用的内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.