【问题标题】:PySide6 and QThread: how to not overlap two different threads?PySide6 和 QThread:如何不重叠两个不同的线程?
【发布时间】:2021-09-20 20:27:24
【问题描述】:

我正在使用 PySide6 和 QThread 编写一个 GUI 应用程序。我有两个不同的 QThread 对象,它们运行两个长时间运行的作业,它们不能重叠,所以如果一个线程正在运行,第二个必须等到第一个结束,如何获得这个?

我尝试写一个简单的代码示例:

from PySide6.QtCore import QThread
from MyJobs import LongJob

job_a = LongJob()
job_b = LongJob()

thread_a = QThread()
thread_b = QThread()

job_a.moveToThread(thread_a)
job_b.moveToThread(thread_b)

thread_a.start()
thread_b.start() # if thread_a is running, thread_b must wait until thread_a ends, then run and viceversa

【问题讨论】:

    标签: python multithreading pyside pyside6


    【解决方案1】:

    线程是工作空间,而您想要管理作业的执行方式。在这种情况下,必须管理任务 B 在任务 A 完成时执行,反之亦然,使用信号。

    import random
    import time
    
    from PySide6.QtCore import QCoreApplication, QObject, QThread, QTimer, Qt, Signal, Slot
    
    
    class LongJob(QObject):
        started = Signal()
        finished = Signal()
    
        @Slot()
        def run_task(self):
            assert QThread.currentThread() != QCoreApplication.instance().thread()
            self.started.emit()
            self.long_task()
            self.finished.emit()
    
        def long_task(self):
            t = random.randint(4, 10)
            print(f'identifier: {self.property("identifier")}, delay: {t} seconds')
            for i in range(t):
                time.sleep(1)
                print(f"{i+1} seconds")
    
    
    if __name__ == "__main__":
        import sys
    
        app = QCoreApplication(sys.argv)
    
        job_a = LongJob()
        job_a.setProperty("identifier", "job_a")
        job_b = LongJob()
        job_b.setProperty("identifier", "job_b")
    
        thread_a = QThread()
        thread_a.start()
        job_a.moveToThread(thread_a)
    
        thread_b = QThread()
        thread_b.start()
        job_b.moveToThread(thread_b)
    
        job_a.finished.connect(job_b.run_task, Qt.QueuedConnection)
        job_b.finished.connect(job_a.run_task, Qt.QueuedConnection)
    
        # start task
        QTimer.singleShot(0, job_a.run_task)
    
        sys.exit(app.exec())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      • 1970-01-01
      相关资源
      最近更新 更多