PyQt5线程休眠和唤醒

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jeekmary/article/details/88739498

在上一篇文章中我有写线程的终止 挂起和唤醒,下面这个例子是线程的休眠和唤醒,是通过线程内一个私有的属性来进行的,读者可以直接将代码跑起来
注:网上搜索的资源

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from PyQt5.QtCore import QThread, QWaitCondition, QMutex, pyqtSignal
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton, QProgressBar

class Thread(QThread):

    valueChange = pyqtSignal(int)

    def __init__(self, *args, **kwargs):
        super(Thread, self).__init__(*args, **kwargs)
        self._isPause = False
        self._value = 0
        self.cond = QWaitCondition()
        self.mutex = QMutex()

    def pause(self):
        print("线程休眠")
        self._isPause = True

    def resume(self):
        print("线程启动")
        self._isPause = False
        self.cond.wakeAll()

    def run(self):
        while 1:
            self.mutex.lock()
            if self._isPause:
                self.cond.wait(self.mutex)
            if self._value > 100:
                self._value = 0
            self._value += 1
            self.valueChange.emit(self._value)
            self.msleep(100)
            self.mutex.unlock()


class Window(QWidget):

    def __init__(self, *args, **kwargs):
        super(Window, self).__init__(*args, **kwargs)
        layout = QVBoxLayout(self)
        self.progressBar = QProgressBar(self)
        layout.addWidget(self.progressBar)
        layout.addWidget(QPushButton('休眠', self, clicked=self.doWait))
        layout.addWidget(QPushButton('唤醒', self, clicked=self.doWake))

        self.t = Thread(self)
        self.t.valueChange.connect(self.progressBar.setValue)
        self.t.start()

    def doWait(self):
        self.t.pause()

    def doWake(self):
        self.t.resume()


if __name__ == '__main__':
    import sys
    import cgitb
    sys.excepthook = cgitb.enable(1, None, 5, '')
    from PyQt5.QtWidgets import QApplication
    app = QApplication(sys.argv)
    w = Window()
    w.show()
    sys.exit(app.exec_())

展开阅读全文

没有更多推荐了,返回首页