0

我正在使用 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
4

1 回答 1

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())
于 2021-07-11T14:33:14.467 回答