Suppose your application needs to run a function in multiple threads the number of which is more than the number of CPU cores/threads. One way is to use QtConcurrent
and setting the maximum thread count :
MyClass *obj = new MyClass;
QThreadPool::globalInstance()->setMaxThreadCount(30);
for(int i=0;i<30;i++)
QtConcurrent::run(obj, &MyClass::someFunction);
Another way is to have multiple objects and move them to different threads using moveToThread
:
for(int i=0;i<30;i++)
{
MyClass *obj = new MyClass;
QThread *th = new QThread();
obj->moveToThread(th);
connect(th, SIGNAL(started()), obj, SLOT(someFunction()) );
connect(obj, SIGNAL(workFinished()), th, SLOT(quit()) );
connect(th, SIGNAL(finished()), obj, SLOT(deleteLater()) );
connect(th, SIGNAL(finished()), th, SLOT(deleteLater()) );
th->start();
}
As the number of threads are more than the number of CPU cores, the threads should be switched between different cores when running.
The question is whether the two approaches have different performances or not? i.e does switching of a QThread
differ from one that is run using QtConcurrent::run
?