You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用QMutex后程序无报错自动停止,求问题排查及优化方案

问题排查与优化方案

核心问题分析

  • 未定义变量触发崩溃:MainWindow中的__thread变量从未初始化,但在stop_search和search_complete中调用了self.__thread.resume(),直接引发AttributeError,导致程序无提示停止运行。
  • QMutex/QWaitCondition用法错误:Search_Thread中的mutex和cond是类静态属性,所有线程实例会共享该资源,极易引发竞态条件;且run方法中锁的范围过大,嵌套循环内频繁调用wait,逻辑混乱。
  • 强制终止线程存在风险:使用QThread.terminate()强制终止线程,可能导致线程持有的资源无法正常释放,甚至引发程序异常崩溃。
  • 频繁更新UI导致卡顿:嵌套循环内每秒多次发送trigger信号更新界面,主线程被大量UI更新任务占用,直接引发界面卡顿。

修复与优化后的代码

import time
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtCore import QWaitCondition, QMutex, pyqtSignal, QThread
from PyQt5.QtWidgets import QMainWindow, QMessageBox, QApplication, QDesktopWidget
import sys


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout.addWidget(self.pushButton)
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setObjectName("label")
        self.horizontalLayout.addWidget(self.label)
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setObjectName("pushButton_2")
        self.horizontalLayout.addWidget(self.pushButton_2)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "Start"))
        self.label.setText(_translate("MainWindow", "0"))
        self.pushButton_2.setText(_translate("MainWindow", "Stop"))


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.search_running = False
        self.search_thread = None
        self.ui.pushButton.clicked.connect(self.start_search)
        self.ui.pushButton_2.clicked.connect(self.stop_search)

    def stop_search(self):
        if self.search_running and self.search_thread:
            reply = QMessageBox.information(self, 'Notice', 'Do you want to stop searching?',
                                            QMessageBox.Yes | QMessageBox.Cancel)
            if reply == QMessageBox.Yes:
                self.search_thread.stop()
                self.search_running = False
                self.ui.pushButton.setEnabled(True)
        else:
            QMessageBox.information(self, 'Tip', 'No ongoing search!', QMessageBox.Ok)

    def start_search(self):
        if not self.search_running:
            self.search_running = True
            self.ui.pushButton.setEnabled(False)
            self.search_thread = Search_Thread()
            self.search_thread.trigger.connect(self.update_label)
            self.search_thread.complete.connect(self.search_complete)
            self.search_thread.start()

    def update_label(self, value):
        self.ui.label.setText(str(value))

    def search_complete(self):
        self.search_running = False
        self.ui.pushButton.setEnabled(True)
        QMessageBox.information(self, 'Tip', 'Search completed!', QMessageBox.Ok)


class Search_Thread(QThread):
    trigger = pyqtSignal(int)
    complete = pyqtSignal()

    def __init__(self):
        super().__init__()
        self._is_running = True
        # 改为实例属性,避免跨线程共享资源引发冲突
        self.mutex = QMutex()
        self.cond = QWaitCondition()
        self._pause = False

    def run(self):
        total = 0
        # 控制UI更新频率,减少主线程压力
        update_interval = 1000  # 每1000次循环更新一次界面
        count = 0
        try:
            for i in range(10000):
                if not self._is_running:
                    break
                for j in range(10000):
                    if not self._is_running:
                        break
                    for k in range(10000):
                        if not self._is_running:
                            break
                        # 线程暂停逻辑
                        self.mutex.lock()
                        while self._pause and self._is_running:
                            self.cond.wait(self.mutex)
                        self.mutex.unlock()

                        total = i + j + k
                        count += 1
                        # 达到更新间隔才发送信号
                        if count >= update_interval:
                            self.trigger.emit(total)
                            count = 0
                        # 模拟耗时操作,避免空循环占用过高CPU
                        time.sleep(0.0001)
        finally:
            # 确保线程退出前发送最终结果
            self.trigger.emit(total)
            self.complete.emit()

    def stop(self):
        # 通过标志位安全终止线程,替代强制terminate
        self._is_running = False
        # 唤醒暂停的线程,确保线程能正常退出循环
        self.resume()
        self.wait()

    def pause(self):
        self.mutex.lock()
        self._pause = True
        self.mutex.unlock()

    def resume(self):
        self.mutex.lock()
        self._pause = False
        self.cond.wakeAll()
        self.mutex.unlock()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    screen = QDesktopWidget().screenGeometry()
    height = 100
    width = 300
    window.setGeometry(int((screen.width() - width) / 2), int((screen.height() - height) / 2), width, height)
    window.setWindowTitle("Multi-thread Test")
    window.show()
    sys.exit(app.exec())

关键优化点说明

  • 修复未定义变量问题:移除原代码中不存在的__thread调用,直接通过线程实例的方法控制运行状态。
  • 正确使用线程同步工具:将mutex和cond改为线程实例属性,暂停逻辑通过_pause标志位配合wait实现,确保线程安全。
  • 安全终止线程:用_is_running标志位替代terminate(),线程在循环中主动检查标志位并退出,避免资源泄漏。
  • 优化UI更新频率:设置update_interval,每N次循环才发送一次更新信号,减少主线程UI更新压力,彻底解决界面卡顿问题。
  • 增加异常保障:线程run方法中加入try-finally块,确保无论线程正常结束还是异常退出,都会发送完成信号并更新最终结果。

内容的提问来源于stack exchange,提问作者高永献

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 16:40:34