我正在Windows上运行python示例代码,每次执行计时器线程后,都会使用如下所示创建一个新线程,但是旧线程从未回收,这确实使线程数量不断增加,这困扰着我担心我的软件不久或将来会消耗掉整个PC内存。我看到其他许多人也遇到了相同的问题,当使用pydev进行调试时,最终会报告为“ TclError:堆栈空间不足”!
这是我的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?)
下面是我的代码,它设置一个计时器,然后调用“循环”功能
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()
答案 0 :(得分:0)
您的代码未在我的Python上执行。触发计时器线程后,无需取消它。换一个新的。另外,将第一次创建的Timer放在初始化例程中,然后等待它执行处理功能会更清洁:
flatDir {
dirs 'libs'
}
所有Timer线程在触发后终止,以后将被垃圾回收。它们不会填满所有可用的内存。