Managing a bunch of QObject-QThreads pairs?
-
Hi, I have a
QObjectderived subclassMasterObjectthat contains a bunch ofQObjectderived subclassWorkerObject. TheWorkerObjecthas 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 ofWorkerObjectduring run-time and so I have created a slot inMasterObjectto 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
WorkerObjectand it's relatedQThread?Also, the
WorkerObjecthas just one slotcalculateValues(...)which does the calculation. Let's say, I have 10WorkerObjectin 10QThreadin myMasterObjectbut 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 dormantWorkerObjectbe consuming any computing power?P.S. I know I can use
QThreadPoolandQRunnableto 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-criticalMasterObjectand it'sWorkerObjectI can assignQThread::LowPriorityfrom the beginning.