所有任务的单个工作线程还是多个特定工作人员?

2022-01-12 00:00:00 python multithreading pyqt pyqt5 qt

问题描述

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

I'm creating a simple GUI application using PyQt5 where I request some data from an API which is then used to populate various controls of the UI.

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

The examples I was following about worker threads in PyQt all seem to sub-class QThread and then do their business logic in the overridden run() method. This works fine but I want to execute different API calls at different times using a worker.

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

So my question is: do I need to create a specific worker thread for every operation I wish to do or is there a way of having a single thread class that I can use to carry out different operations at different times and therefore avoid the overhead of creating different thread sub-classes?


解决方案

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

What you can do is design an object to do all these tasks (inherit QObject for slots / signals). Lets say each task is defined as a separate function - lets designate these functions as slots.

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

Then (a general order of events):

  • 实例化一个 QThread 对象.
  • 实例化你的类.
  • 使用 YouClass->moveToThread(pThread) 将您的对象移动到线程中.
  • 现在为每个插槽定义一个信号,并将这些信号连接到对象中的相关插槽.
  • 最后使用 pThread->start()
  • 运行线程
  • instantiate a QThread object.
  • instantiate your class.
  • Move your object into the thread using YouClass->moveToThread(pThread).
  • Now define a signal for each slot and connect these signals to the relevant slots in your object.
  • Finally run the thread using pThread->start()

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

Now you can emit a signal to do a particular task in the thread. You do not need to sub-class QThread just use a normal class derived from QObject (so that you can use slots/signals).

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

You can either use one class in one thread to do many operations (note: they will be queued). Or make many classes in many threads (to run "parallel").

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

I don't know python well enough to attempt an example here so I won't :o

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

Note: The reason to sub-class QThread would be if you wanted to extend the functionality of the QThread class - i.e. add more/specific thread-related functions. QThread is a class that controls a thread, and is not meant to be used to run arbitrary/generic tasks... even though you can abuse it to do so if you wish :)

相关文章