适用于所有任务的单个工作线程还是多个特定的工作线程? [英] Single worker thread for all tasks or multiple specific workers?
问题描述
我正在使用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 :)
这篇关于适用于所有任务的单个工作线程还是多个特定的工作线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!