Managing a bunch of QObject-QThreads pairs?
-
Hi, I have a
QObject
derived subclassMasterObject
that contains a bunch ofQObject
derived subclassWorkerObject
. TheWorkerObject
has to perform long-running calculations and so I create a thread for each of these and usemoveToThread()
to move these objects to the new thread. I have to manage the number ofWorkerObject
during run-time and so I have created a slot inMasterObject
to manage the number ofWorkerObject
. The problem is, I am having a hard time understanding how to properly manage the number ofWorkerObject
. Currently, I have the following code:MasterObject.h
... QList<WorkerObject*> workers; QList<QThread*> workerThreads; public slots: void setNumberOfWorkers(int num);
MasterObject.cpp
... MasterObject::~MasterObject() { if(!workers.isEmpty()){ for(int ii = 0; ii < workers.length(); ++ii){ delete workers[ii]; delete workerThreads[ii]; } workers.clear(); workerThreads.clear(); } } void MasterObject::setNumberOfWorkers(int num) { if(workers.isEmpty()){ for(int ii = 0; ii < num; ++ii){ workers << new WorkerObject(); workerThreads << new QThread(this); workers[ii]->moveToThread(workerThreads[ii]); workerThreads[ii]->start(); } } else{ if(num > workers.length()){ for(int ii = workers.length(); ii < num; ++ii){ workers << new WorkerObject(); workerThreads << new QThread(this); workers[ii]->moveToThread(workerThreads[ii]); workerThreads[ii]->start(); } } else if(num < workers.length()){ for(int ii = workers.length() - 1; ii >= num; --ii){ delete workers[ii]; workers.removeLast(); delete workerThreads[ii]; workerThreads.removeLast(); } } } }
Is this the correct approach to manage the
WorkerObject
and it's relatedQThread
?Also, the
WorkerObject
has just one slotcalculateValues(...)
which does the calculation. Let's say, I have 10WorkerObject
in 10QThread
in myMasterObject
but I only need to perform 3 calculations. Then what will happen to the rest of the 7WorkerObject
? I am assuming since I am not calling theircalculateValues()
slot, they will be sleeping all the time. Is this the case? Will these 7 dormantWorkerObject
be consuming any computing power?P.S. I know I can use
QThreadPool
andQRunnable
to achieve a similar condition without having to manage the threads myself, but I want to be able to set the thread priority, so that for non-criticalMasterObject
and it'sWorkerObject
I can assignQThread::LowPriority
from the beginning.