c++multithreadingqtqthreadqtconcurrent

Multithreading performance of QtConcurrent Vs QThread with many threads


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 ?


Solution

  • I agree with first answer, but I want to add something.

    QThread is low-level class which just run OS-specific functions. What is the QtConcurrent? The answer is in Qt source code.

    First level: run

    QFuture<T> run(T (*functionPointer)())  
    {
            return (new StoredFunctorCall0<T, T (*)()>(functionPointer))->start();
    }
    

    Second:

    struct StoredFunctorCall0: public RunFunctionTask<T>    { ...
    

    Third:

    template <typename T>
    class RunFunctionTaskBase : public QFutureInterface<T> , public QRunnable
    { ...
    

    Now about QRunnable. When we start QRunnable with QThreadPool we do:

    start() which calls tryStart() which calls startThread() which operate with QThreadPoolThread (and it is a QThread subclass) and it is finally call start() of QThread.

    And of course this chain is not full, long road, isn't it? So as I know, when we use abstraction, we have abstraction penalty (QtConcurrent has bigger penalty then QThread), but final result is same, it is QThread.