2016-06-15 04:02:01

PyQt4 QThread QMutex 多线程及锁

from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
class Windows(QDialog):
    def __init__(self, parent=None):
        super(Windows, self).__init__(parent)
        self.startButton = QPushButton("Start")
        self.stopButton = QPushButton("Stop")
        self.stopButton.setEnabled(False)
        self.statusLable = QLabel("Please click \"start\"")
        self.statusLable.setFrameStyle(QFrame.StyledPanel|
                                         QFrame.Plain)
        topLayout = QHBoxLayout()
        topLayout.addWidget(self.startButton)
        topLayout.addWidget(self.stopButton)
        layout = QVBoxLayout()
        layout.addLayout(topLayout)
        layout.addWidget(self.statusLable)
        # self.timer = Timer()
        self.connect(self.startButton, SIGNAL("clicked()")
                        , self.start)
        self.connect(self.stopButton, SIGNAL("clicked()")
                        , self.stop)
        self.setLayout(layout)
        self.setWindowTitle("Timer")
        self.setWindowFlags(Qt.WindowMinimizeButtonHint)
        self.Threadx=[]
    def updateTime(self):
        self.statusLable.setText("Time: %s s" % QString.number(self.sec))
        self.sec += 1
    def start(self):
        self.sec = 0
        self.startButton.setEnabled(False)
        self.stopButton.setEnabled(True)
        for i in xrange(0,30):
            self.Threadx.append(Timer())
            self.connect(self.Threadx[i], SIGNAL("updateTime()")
                        , self.updateTime)
            self.Threadx[i].start()
    def stop(self):
        for i in self.Threadx:
            i.stop()
        self.stopButton.setEnabled(False)
        self.startButton.setEnabled(True)
        self.statusLable.setText("Timer stoped.")
ssss=0
class Timer(QThread):
    def __init__(self, parent=None):
        super(Timer, self).__init__(parent)
        self.stoped = False
        self.mutex = QMutex()
    def run(self):
        global ssss
        with QMutexLocker(self.mutex):
            self.stoped = False
        while True:
            if self.stoped:
                return
            self.emit(SIGNAL("updateTime()"))
            ssss+=1
            print '\n%d'%ssss
            self.sleep(1)
    def stop(self):
        print '\n%d'%ssss
        with QMutexLocker(self.mutex):
            self.stoped = True
    def isStoped(self):
        with QMutexLocker(self.mutex):
            return self.stoped
app = QApplication(sys.argv)
windows = Windows()
windows.show()
app.exec_()
发表回复