等待当前正在执行的线程死亡

时间:2014-10-29 21:16:06

标签: python multithreading pyqt queue python-multithreading

我已经编写了一个python代码,每按一次按钮,我在2个线程的帮助下执行我的工作。 例如

 Press button 1 -> Thread-1 and Thread-2 will do the job
 Press button 2 -> Thread-3 and Thread-4 will do the job
 Press button 3 -> Thread-5 and Thread-6 will do the job

每当按下按钮,直到它不打印屏幕上的o / p时,按钮显示“WIP”(正在进行中)

我想进一步修改它, 当按下任何按钮时,我不希望用户在一个按钮正在进行时按下更多按钮(WIP)。 因此,在当前工作的两个终止之前不应创建其他线程。 我该怎么做?

我在这里提供我的代码供参考:

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys, os, time
import Queue
import threading

class LearnButton(QPushButton):
    def __init__(self, title, test):
        super(QPushButton, self).__init__()
        self._title = title
        self._test = test
        self.setText(title)
        self.clicked.connect(self.click_threads)
        self._q = Queue.Queue()
        self.flag = True

    def click_threads(self):
        self.thread1 = threading.Thread(target=self.fun1)
        self.thread2 = threading.Thread(target=self.fun2)
        self.thread1.start()
        self.thread2.start()

    def fun1(self):
        print "Val", self._test, self._title, type(self._test), type(self._title)
        self.date_time_string = time.strftime("%Y%m%d_%H%M%S")
        self.retainedv = self.date_time_string
        print self.date_time_string
        self.flag = False


    def fun2(self):
        print "Val", self._test, self._title, type(self._test), type(self._title)
        self.setEnabled(False)
        while self.thread1.isAlive():
            self.setText('WIP')
            time.sleep(0.5)
        self.setEnabled(True)
        self.setText(self._title)


class LearnApp(QDialog):
    def __init__(self):
        super(QDialog, self).__init__()
        self.setWindowTitle("LearnApp")

        close_button = QPushButton("Close")
        close_button.clicked.connect(self.close)
        self.button1 = LearnButton("B1", "Im in B1")
        self.button2 = LearnButton("B2", "Im in B2")
        self.button3 = LearnButton("B3", "Im in B3")

        self.test_report = QTextEdit()
        self.test_report.setReadOnly(True)
        layout = QHBoxLayout()        
        sub_layout = QVBoxLayout()
        sub_layout.addWidget(self.button1)
        sub_layout.addWidget(self.button2)
        sub_layout.addWidget(self.button3)
        sub_layout.addWidget(close_button)
        layout.addLayout(sub_layout)
        layout.addWidget(self.test_report)
        self.setLayout(layout)
        self.setFocus()


app = QApplication(sys.argv)
dialog = LearnApp()
dialog.show()
app.exec_()

1 个答案:

答案 0 :(得分:0)

您需要线程发出用于暂停GUI的信号。 由于您将使用Qt信号/插槽机制,因此您不应使用Python threading模块。 PyQt有自己的线程模块(例如QThreading)。

请参阅:Threading in a PyQt application: Use Qt threads or Python threads?