PyQt QThread内存泄漏

时间:2014-08-06 09:45:28

标签: 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)
        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_())

它可以是什么?

0 个答案:

没有答案