Python 2.7,线程.计时器生成太多未回收的垃圾线程



我在我的窗口上运行一个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:Python27libthreading.py", line 801, in __bootstrap_inner
self.run()
File "C:Python27libthreading.py", line 1073, in run
self.function(*self.args, **self.kwargs)
File "D:worktoolseclipseWorkspacetimerTest.py", line 46, in handle_function
self.hFunction()
File "D:worktoolseclipseWorkspacetimerTest.py", line 56, in printer
lab['text'] = clock
File "C:Python27liblib-tkTkinter.py", line 1337, in __setitem__
self.configure({key: value})
File "C:Python27liblib-tkTkinter.py", line 1330, in configure
return self._configure('configure', cnf, kw)
File "C:Python27liblib-tkTkinter.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()

您的代码不会在我的Python上执行。一旦Timer线程启动,就没有必要取消它。只要做一个新的。此外,只需将第一个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线程在触发后终止,稍后将被垃圾回收。它们不会填满所有可用的内存。

最新更新