问题描述
使用pyside2
,我有一个运行后台事件循环的辅助线程。关闭应用程序后,我想quit()
辅助线程并为其wait()
完成其事件。
但是,一旦我调用wait()
,我的应用就会出现死锁(或其他问题)。为了演示此问题,我创建了一个带有子类QThread
的小型示例应用程序,该应用程序通过调用exec_()
运行事件循环,然后使用一些模拟清理打印来模拟长时间退出。
import sys
import time
from pyside2.QtCore import QThread
from pyside2.QtWidgets import QApplication,QMainWindow
class AuxThread(QThread):
def __init__(self):
super().__init__()
def run(self):
print("Starting AuxThread")
self.exec_()
print("Stopping AuxThread")
iteration = 0
# Simulate a long time for thread finish
while iteration < 100:
iteration += 1
print(f"{iteration} cleanup loops in {QThread.currentThread()}")
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.thread().setobjectName("main thread")
self.aux_thread = AuxThread()
self.aux_thread.setobjectName("aux thread")
self.aux_thread.start()
def closeEvent(self,event):
print(f"Quitting aux_thread from {QThread.currentThread()}")
self.aux_thread.quit()
# Increasing this time allows the run() function to complete
# If this time is too short,then execution hangs forever
time.sleep(0.001)
print(f"blocking thread {QThread.currentThread()}")
self.aux_thread.wait()
print(f"aux_thread is joined")
if __name__ == "__main__":
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
Starting AuxThread
Quitting aux_thread from <pyside2.QtCore.QThread(0x7fcc9cfd12b0,name = "main thread") at 0x11c4f1580>
Stopping AuxThread
1 cleanup loops in <__main__.AuxThread(0x7fcc9cfe5e40,name = "aux thread") at 0x11c4f15c0>
2 cleanup loops in <__main__.AuxThread(0x7fcc9cfe5e40,name = "aux thread") at 0x11c4f15c0>
... [output elided] ...
72 cleanup loops in <__main__.AuxThread(0x7fcc9cfe5e40,name = "aux thread") at 0x11c4f15c0>
73 cleanup loops in <__main__.AuxThread(0x7fcc9cfe5e40,name = "aux thread") at 0x11c4f15c0>
blocking thread <pyside2.QtCore.QThread(0x7fcc9cfd12b0,name = "main thread") at 0x11c4f1580>
docs说QThread.wait()
“阻塞线程,直到QThread完成执行(即当它从run()
返回时)”
有趣的是,他们没有提到这里阻塞了哪个线程,但是阻塞正在等待的QThread并没有任何意义。我认为aux_thread.wait()
应该只阻塞主线程,为什么一旦调用wait()
时就阻塞了aux线程中的执行?
我想念什么?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)