Python PyQt QThread内存泄漏
python 2.7.6 PyQt 4.10.3 应用程序创建许多线程,然后尝试删除它们。但是分配的内存越来越大。。。代码如下:Python PyQt QThread内存泄漏,python,memory-leaks,pyqt,qthread,Python,Memory Leaks,Pyqt,Qthread,python 2.7.6 PyQt 4.10.3 应用程序创建许多线程,然后尝试删除它们。但是分配的内存越来越大。。。代码如下: # -*- coding: utf-8 -*- from PyQt4 import QtCore, QtGui import sys class MyThread(QtCore.QThread): def __init__(self, parent, n): QtCore.QThread.__init__(self) se
# -*- coding: utf-8 -*-
from PyQt4 import QtCore, QtGui
import sys
class MyThread(QtCore.QThread):
def __init__(self, parent, n):
QtCore.QThread.__init__(self)
self.parent_ = parent
self.n = n
#self.connect(self, QtCore.SIGNAL("finished()"), self, QtCore.SLOT("deleteLater()")) - if uncomment - dies with """QThread::wait: Thread tried to wait on itself QThread: Destroyed while thread is still running""" messages
def run(self):
print self.n #just prints the number thread was initialized with
self.emit(QtCore.SIGNAL("signalMyThread(PyQt_PyObject)"), {'result': 'ok', 'n': self.n})
class Application(QtGui.QApplication):
def __init__(self, argv):
QtGui.QApplication.__init__(self, argv)
self.prepare()
def prepare(self):
self.threads_ = {}
self.working_threads = 0
self.n = -1
for x in xrange(50):
QtCore.QTimer().singleShot(100, self.start) #starts 50 simple threads
def start(self):
self.n += 1
if self.n > 1000000000:
QtCore.QTimer().singleShot(100, self.finish)
return
n = self.n
QtCore.QTimer().singleShot(100, lambda: self.start2(n)) #every thread initialized with his own number
def start2(self, n):
self.threads_[n] = MyThread(self, n) #creating thread
self.threads_[n].moveToThread(self.threads_[n])
self.connect(self.threads_[n], QtCore.SIGNAL("signalMyThread(PyQt_PyObject)"), self.receive)
self.working_threads += 1
self.threads_[n].start() # and starting
def receive(self, result):
n = result.get('n')
QtCore.QTimer().singleShot(100, lambda: self.killThread(n))
QtCore.QTimer().singleShot(100, self.start)
def killThread(self, n):
if n not in self.threads_:
return
if self.threads_[n].isRunning():
QtCore.QTimer().singleShot(100, lambda: self.killThread(n))
return
self.threads_[n].deleteLater() #killing thread when it's done. I tried to use .quit(), but there's no effect
self.threads_.pop(n, None)
self.working_threads -= 1
def finish(self):
if self.working_threads > 0:
QtCore.QTimer().singleShot(100, self.finish)
return
self.quit()
if __name__=='__main__':
app = Application(sys.argv)
sys.exit(app.exec_())
它可以是什么?您似乎试图将
QThread
子类化,并同时使用moveToThread
(您试图将QThread
的实例移动到自身中)。使用一种或另一种方法,moveToThread
是首选方法。请参阅,以获取每种方法的示例。@user3419537您应该将您的注释作为一个答案,因为它正确地识别了错误和修复。我也注意到了moveToThread
的错误,但在我尝试调试它时,它仍然泄漏了内存。