PySide6和QThread:如何避免两个不同的线程重叠?

2024-09-25 00:30:01 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 对象代码fromimport应用程序作业jobgui
1条回答
网友
1楼 · 发布于 2024-09-25 00:30:01

线程是工作空间,您需要管理作业的执行方式。在这种情况下,任务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())

相关问题 更多 >