欢迎访问宙启技术站
智能推送

PyQt5.QtCoreQMutex()的使用示例:实现线程安全的计数器

发布时间:2024-01-10 01:34:05

PyQt5.QtCore.QMutex()是PyQt5中的一个类,用于实现线程安全的锁,可以确保多个线程在访问共享资源时的互斥性。

下面是一个使用PyQt5.QtCore.QMutex()实现线程安全的计数器的例子:

import sys
from PyQt5.QtCore import Qt, QMutex, QMutexLocker, QThread, pyqtSignal
from PyQt5.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget, QPushButton


class CounterThread(QThread):
    update_counter = pyqtSignal(int)

    def __init__(self):
        super().__init__()
        self.mutex = QMutex()
        self.counter = 0

    def run(self):
        while True:
            with QMutexLocker(self.mutex):
                self.counter += 1
                self.update_counter.emit(self.counter)
            self.msleep(100)


class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()
        self.label = QLabel("0")
        layout.addWidget(self.label)

        self.start_button = QPushButton("Start")
        self.start_button.clicked.connect(self.start_counter)
        layout.addWidget(self.start_button)

        self.stop_button = QPushButton("Stop")
        self.stop_button.setEnabled(False)
        self.stop_button.clicked.connect(self.stop_counter)
        layout.addWidget(self.stop_button)

        self.setLayout(layout)

        self.thread = CounterThread()
        self.thread.update_counter.connect(self.update_counter)

    def start_counter(self):
        self.start_button.setEnabled(False)
        self.stop_button.setEnabled(True)
        self.thread.start()

    def stop_counter(self):
        self.start_button.setEnabled(True)
        self.stop_button.setEnabled(False)
        self.thread.terminate()

    def update_counter(self, count):
        self.label.setText(str(count))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

在这个例子中,我们定义了一个CounterThread类,继承自QThread。在CounterThread的构造方法中,我们创建了一个QMutex对象来实现线程之间的互斥访问。在run方法中,我们使用QMutexLocker来确保在对counter进行操作时只有一个线程可以进行,避免了多线程的竞态条件。

在MainWindow类中,我们创建了一个CounterThread对象,并通过信号槽机制将更新计数器的信号连接到更新界面的槽函数。通过点击Start按钮可以启动计数器线程,并且在界面上显示计数值。点击Stop按钮可以停止计数器线程。

通过使用QMutex来实现线程安全的锁,我们可以确保在多线程的环境中对共享资源的互斥访问,从而避免了竞态条件的发生。这对于需要在多线程中访问共享资源的应用程序非常重要。