Qt Threading and Concurrency QtConcurrent Run


Example

If you find managing QThreads and low-level primitives like mutexes or semaphores too complex, Qt Concurrent namespace is what you are looking for. It includes classes which allow more high-level thread management.

Let's look at Concurrent Run. QtConcurrent::run() allows to run function in a new thread. When would you like to use it? When you have some long operation and you don't want to create thread manually.

Now the code:

#include <qtconcurrentrun.h>

void longOperationFunction(string parameter)
{
    // we are already in another thread
    // long stuff here
} 

void mainThreadFunction()
{
    QFuture<void> f = run(longOperationFunction, "argToPass");
    f.waitForFinished();
}

So things are simple: when we need to run another function in another thread, just call QtConcurrent::run, pass function and its parameters and that's it!

QFuture presents the result of our asynchronous computation. In case of QtConcurrent::run we can't cancel the function execution.