[英]What is the purpose of “threads” list variable when used with Queue
If a list variable threads
is not declared (or if it is declared outside of class or declared as a local) the code throws: 如果未声明列表变量threads
(或者如果声明在类之外或声明为本地变量),则代码将抛出:
QThread: Destroyed while thread is still running
[Finished in 4.4s with exit code -11]
Yet, it appears it doesn't do anything other than allowing to append Thread instance to itself. 但是,看起来除了允许将Thread实例附加到自身之外,它没有做任何其他事情。 What is the purpose of this variable? 这个变量的目的是什么? Why it is needed and where I could read more about it? 为什么需要它,在哪里可以阅读更多有关它的信息?
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_())
A QThread
, unlike a threading.Thread
, gets terminated as soon as there are no more references to it. QThread
与threading.Thread
不同,它在没有更多引用时会立即终止。 Sticking the QThread
instance in a global list or a list that's an instance variable of a long-lived class will preserve a reference to the thread, and prevent it from being destroyed. 将QThread
实例粘贴在全局列表或长期存在的类的实例变量的列表中将保留对该线程的引用,并防止该线程被破坏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.