Super easy C++ multi-threaded applications with Qt 6 and Concurrent

The application conceptually might look like…

This is where Qt really can help!

In my Qt 6Core Advanced Course on Udemy, I deep dive into this subject, but let’s take a look at how we can use Qt to solve this issue — this may look confusing but don’t worry Qt makes the code much easier…

At a high level, we will:

Run our main function, at some point we will want a value, but we want to move that function generating the value to another thread, and when we are ready we will get the value back from the function in the future.

Step 1 — Add the Qt Concurrent module to CMake

cmake_minimum_required(VERSION 3.14)project(qt6ca-3-20 LANGUAGES CXX)set(CMAKE_INCLUDE_CURRENT_DIR ON)set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(QT NAMES Qt6 Qt5 COMPONENTS Core Concurrent REQUIRED)
find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core Concurrent REQUIRED)
add_executable(qt6ca-3-20
main.cpp
)
target_link_libraries(qt6ca-3-20 Qt${QT_VERSION_MAJOR}::Core Qt${QT_VERSION_MAJOR}::Concurrent)
#include <QCoreApplication>
#include <QDebug>
#include <QFuture>
#include <QFutureWatcher>
#include <QList>
#include <QtConcurrent>
int multiply(const int &value)
{
qInfo() << "Called: " << value;
int num = value * 10;
return num;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QList<int> list;
for (int i = 0;i < 100; i++)
{
list.append(i);
}
QFutureWatcher<int> watcher;
QFuture<int> future = QtConcurrent::mapped(list,&multiply);
watcher.setFuture(future);

//Set signals and slots here
qInfo() << "Back in main!"; //Do other things with the watcher if needed
watcher.waitForFinished();
qInfo() << "Done!";
qInfo() << future.results();
return a.exec();
}
QFutureWatcher<int> watcher;
QFuture<int> future = QtConcurrent::mapped(list,&multiply);
watcher.setFuture(future);
//Do other things with the watcher if needed
watcher.waitForFinished();
...
qInfo() << future.results();

See this is easy!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store