【问题标题】:Single worker thread for all tasks or multiple specific workers?所有任务的单个工作线程还是多个特定工作人员?
【发布时间】:2016-10-07 20:01:09
【问题描述】:

我正在使用 PyQt5 创建一个简单的 GUI 应用程序,我从 API 请求一些数据,然后用于填充 UI 的各种控件。

我在 PyQt 中关注的有关工作线程的示例似乎都是 QThread 的子类,然后在覆盖的 run() 方法中执行它们的业务逻辑。这工作正常,但我想使用工作人员在不同时间执行不同的 API 调用。

所以我的问题是:我是否需要为我希望执行的每个操作创建一个特定的工作线程,或者是否有一种方法可以让我可以使用单个线程类在不同的时间执行不同的操作,从而避免创建不同线程子类的开销?

【问题讨论】:

  • 你不应该继承QThread。相反,使用QtConcurrent::run,或者可能是QObject 的子类,并将这些工作对象移动到单个工作线程。

标签: python multithreading qt pyqt pyqt5


【解决方案1】:

您可以做的是设计一个对象来完成所有这些任务(为插槽/信号继承 QObject)。假设每个任务都定义为一个单独的函数 - 让我们将这些函数指定为插槽。

那么(事件的一般顺序):

  • 实例化一个 QThread 对象。
  • 实例化你的类。
  • 使用YouClass->moveToThread(pThread) 将您的对象移动到线程中。
  • 现在为每个插槽定义一个信号,并将这些信号连接到对象中的相关插槽。
  • 最后使用pThread->start()运行线程

现在您可以发出信号以在线程中执行特定任务。您不需要子类 QThread 只需使用从 QObject 派生的普通类(这样您就可以使用槽/信号)。

您可以在一个线程中使用一个类来执行许多操作(注意:它们将被排队)。或者在多个线程中创建多个类(以“并行”运行)。

我不太了解python,无法在这里尝试示例,所以我不会:o

注意:子类 QThread 的原因是如果您想扩展 QThread 类的功能 - 即添加更多/特定的线程相关功能。 QThread 是一个控制线程的类,并不意味着用于运行任意/通用任务......即使你可以滥用它来这样做,如果你愿意:)

【讨论】:

  • 很好的答案,尤其是他们暗示作业将自动排队。也许我会为此写一个例子。
  • @Trilarion 谢谢,是的,请随时添加示例:)
【解决方案2】:

这里是一个(但可以任意多个)工作对象的简明示例,该工作对象被移动到单个正在运行的 QThread(已启动)并通过信号进行通信。线程也将在最后停止。它演示了his answer 中概述的 code_fodder。

from PyQt4 import QtCore
QtCore.Signal = QtCore.pyqtSignal

class Master(QtCore.QObject):

    command = QtCore.Signal(str)

    def __init__(self):
        super().__init__()

class Worker(QtCore.QObject):

    def __init__(self):
        super().__init__()

    def do_something(self, text):
        print('current thread id = {}, message to worker = {}'.format(int(QtCore.QThread.currentThreadId()), text))

if __name__ == '__main__':

    app = QtCore.QCoreApplication([])

    # give us a thread and start it
    thread = QtCore.QThread()
    thread.start()

    # create a worker and move it to our extra thread
    worker = Worker()
    worker.moveToThread(thread)

    # create a master object and connect it to the worker
    master = Master()
    master.command.connect(worker.do_something)

    # call a method of the worker directly (will be executed in the actual thread)
    worker.do_something('wrong way to communicate with worker')

    # communicate via signals, will execute the method now in the extra thread
    master.command.emit('right way to communicate with worker')

    # start the application and kill it after 1 second
    QtCore.QTimer.singleShot(1000, app.quit)
    app.exec_()

    # don't forget to terminate the extra thread
    thread.quit()
    thread.wait(5000)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 2013-11-05
    • 2015-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多