如果未声明列表变量threads
(或者如果它在类之外声明或声明为本地),则代码抛出:
QThread: Destroyed while thread is still running
[Finished in 4.4s with exit code -11]
然而,除了允许将Thread实例附加到自身之外,它似乎没有做任何其他事情。这个变量的目的是什么?为什么需要它以及我可以在哪里阅读更多信息?
from PyQt4 import QtCore, QtGui
import threading
import Queue as queue
app = QtGui.QApplication([])
class SimpleThread(QtCore.QThread):
def __init__(self, queue, parent=None):
QtCore.QThread.__init__(self, parent)
self.queue=queue
def run(self):
while True:
arg=self.queue.get()
self.fun(arg)
self.queue.task_done()
def fun(self, arg):
print 'func: %s'%arg
return arg+1
class AppWindow(QtGui.QMainWindow):
def __init__(self):
super(AppWindow, self).__init__()
mainWidget=QtGui.QWidget()
self.setCentralWidget(mainWidget)
mainLayout = QtGui.QVBoxLayout()
mainWidget.setLayout(mainLayout)
button=QtGui.QPushButton('Process')
button.clicked.connect(self.process)
mainLayout.addWidget(button)
def process(self):
MAX_CORES=2
self.queue=queue.Queue()
self.threads=[]
for i in range(1, MAX_CORES):
thread=SimpleThread(self.queue)
self.threads.append(thread)
thread.start()
for arg in [1,2,3]:
self.queue.put(arg)
window=AppWindow()
window.show()
sys.exit(app.exec_())
答案 0 :(得分:2)
QThread
与threading.Thread
不同,只要没有对它的引用就会终止。将QThread
实例粘贴到全局列表或列出长期类的实例变量的列表中将保留对该线程的引用,并防止其被销毁。