logo MSJO.kr

Qt Concurrent Example

2021-10-08
MsJ
 

Concurrent computing is a form of computing in which several computations are executed concurrently—during overlapping time periods—instead of sequentially—with one completing before the next starts1. 어떠한 프로그래밍 로직이 요청한 결과를 순차적으로 처리하는 것이 아닌 여러 곳의 요청을 동시에 처리하는 것을 말한다.

Concurrency는 Parallelism의 난해함을 풀어낸 방법2인데 대표적인 것이 Coroutine(C#, Unity)이다. Rust 프로그래밍에서 Concurrency 예제3와 Go 프로그래밍에서 Concurrency 예제4는 과거 포스팅한 글에서 볼 수 있다. 이번 예제는 Qt(C++)에서 Concurrency를 구현하는 간단한 예제를 VoidRealms5강좌를 통해 소개하였다.

CMakeLists.txt
cmake_minimum_required(VERSION 3.14)
project(QtExam LANGUAGES CXX)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_CXX_STANDARD 17)
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(QtExam
  main.cpp
)
target_link_libraries(QtExam Qt${QT_VERSION_MAJOR}::Core
    Qt${QT_VERSION_MAJOR}::Concurrent)
#set_target_properties(QtExam PROPERTIES WIN32_EXECUTABLE TRUE)
main.cpp
#include <QCoreApplication>
#include <QFuture>
#include <QRandomGenerator>
#include <QThread>
#include <QtConcurrent>
#include <QtDebug>

void test()
{
    qInfo() << "Test :" << QThread::currentThread();
}

int testRandom(int min, int max)
{
    qInfo() << "Random :" << QThread::currentThread();
    QThread::currentThread()->msleep(3000);
    if (min >= max)
        min = 0;
    return QRandomGenerator::global()->bounded(min, max);
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QThread::currentThread()->setObjectName("Main Thread");

    qInfo() << "Starting :" << QThread::currentThread();

    // Waiting
    QFuture<void> f1 = QtConcurrent::run(test);
    f1.waitForFinished();

    // Returning values
    QFuture<int> f2 = QtConcurrent::run(testRandom, 100, 200);
    qInfo() << "Random Result :" << f2.result();

    qInfo() << "Finished :" << QThread::currentThread();

    return a.exec();
}
Reference
  1. wikipedia, “Concurrent computing”
  2. RAPAPA DEV STORY, “Concurrency와 Parallelism 차이”
  3. MSJO.kr, “Rust, Concurrency and Channels”
  4. MSJO.kr, “Go, REST API with Mux”
  5. VoidRealms, “Qt 6 - Episode 24 - Qt Concurrent”

Prεv(Θld)   Nεxt(Nεw)
Content
Search     RSS Feed     BY-NC-ND