조회 수 12264 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부

 

Qt에서 쓰레드를 생성하는 방법은 몇가지가 있는데 여기서는 QtConcurrent를 이용한 벙법을 소개한다.

예제소스이다

 

 #include <QCoreApplication>
#include <qtconcurrentrun.h>
#include <QThread>

#ifndef QT_NO_CONCURRENT

void myRunFunction(QString name)
{
    for(int i = 0; i <= 5; i++)
    {
        qDebug() << name << " " << i <<
                    "from" << QThread::currentThread();
    }
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QFuture<void> t1 = QtConcurrent::run(myRunFunction, QString("A"));
    QFuture<void> t2 = QtConcurrent::run(myRunFunction, QString("B"));
    QFuture<void> t3 = QtConcurrent::run(myRunFunction, QString("C"));

    t1.waitForFinished();
    t2.waitForFinished();
    t3.waitForFinished();

    return a.exec();
}

#else

#include <QLabel>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QString text("Qt Concurrent is not yet supported on this platform");

    QLabel *label = new QLabel(text);
    label->setWordWrap(true);

    label->show();
    qDebug() << text;

    app.exec();
}
#endif

 

 

 

.pro파일에는 아래와 같은 행을 추가 해야한다.

 

 QT       += concurrent

 

예제에서 볼 수 있듯이 Worker쓰레드를 만들거나 Qthread를 생성할 필요없이 단지 할 일은 적절한 매개변수 전달과 실행될 함수를 정의하는 것이다. 예제에서 QtConcurrent의 아래와 같은 API들을 사용했다.

 

QtConcurrent::run() - 다른 쓰레드에서 함수를 실행한다.

QFuture - 비동기의 결과를 제어하는 클래스이다.

QFuture는 실제로 waitForFinished()<결과를 기다리거나>, result()<결과 값을 확인하거나>, cancel(), pause(), or resume()등의 메소드들을 제공한다.

주의할 점은 QtConcurrent::run()으로 얻은 future객체는 cancel, pause and resum을 지원하지않는다.

 

그러면 MapReduce는 무엇인가.

MapReduce는 대용량 데이터의 병렬처리 알고리즘을 단순화하기 위해 구글에서 고안했다. 

병렬 분산 알고리즘을 사용하여 빅 데이터 세트를 처리하고 생성하기위한 프로그래밍 모델 및 관련 구현인것이다.

 

QtConcurrent 프레임웍은 이러한 병렬처리를 위한 방법으로 mappedReduced를 제공한다.

API는 다음과 같다.

QFuture<T> mappedReduced(list, mapFunction, reducefunction);

 

기본 개념은 알고리즘을 두 부분으로 나누는 것인데,

하나는 입력 데이터의 개별 부분에서 병렬로 실행할 수있는 부분(map)과 또 하나는 결과를 수집하고 최종 결과를 생성하는 하나의 순차적 파트(reduce)가 그것이다.

 

아래는 Qt기본 예제인데 map-reduce 알고리즘을 사용하는 방법을 보여준다.

 

먼저 파일 목록이 입력될 목록으로 사용된다.

QStringList files = findFiles("../../", QStringList() << "*.cpp" << "*.h");

 

그런다음 기본 싱글 쓰레드로 파일 목록의 단어수를 카운팅한다.

typedef QMap<QString, int> WordCount;

WordCount singleThreadedWordCount(const QStringList &files)
{
    WordCount wordCount;
    for (const QString &file : files) {
        QFile f(file);
        f.open(QIODevice::ReadOnly);
        QTextStream textStream(&f);
        while (!textStream.atEnd()) {
            const auto words =  textStream.readLine().split(' ');
            for (const QString &word : words)
                wordCount[word] += 1;
        }
    }
    return wordCount;
}

int singleThreadTime = 0;
{
    QTime time;
    time.start();
    WordCount total = singleThreadedWordCount(files);
    singleThreadTime = time.elapsed();
    qDebug() << "single thread" << singleThreadTime;
}

 

그리고 mappedReduced API를 사용하여 역시 파일목록의 단어수를 카운팅한다.

WordCount countWords(const QString &file)
{
    QFile f(file);
    f.open(QIODevice::ReadOnly);
    QTextStream textStream(&f);
    WordCount wordCount;

    while (!textStream.atEnd()) {
        const auto words =  textStream.readLine().split(' ');
        for (const QString &word : words)
            wordCount[word] += 1;
    }

    return wordCount;
}

void reduce(WordCount &result, const WordCount &w)
{
    QMapIterator<QString, int> i(w);
    while (i.hasNext()) {
        i.next();
        result[i.key()] += i.value();
    }
}

int mapReduceTime = 0;
{
    QTime time;
    time.start();
    WordCount total = mappedReduced(files, countWords, reduce);
    mapReduceTime = time.elapsed();
    qDebug() << "MapReduce" << mapReduceTime;
}

 

위의 예제를 컴파일해서 실행해본 결과이다.

이미지 1.png

 

싱글 쓰레드 카운팅연산에 비해 map-reduce 알고리즘에 의해 처리된 시간이 2배가 넘게 빠른 결과를 보여준다.

 

QtConcurrent 및 MapReduce의 좀더 자세한 내용은 해당사이트를 참고하기 바란다.

http://doc.qt.io/qt-5/qtconcurrent-index.html

 


  1. No Image notice

    Qt프로그래밍(QtQuick) Beginner를 위한 글 읽는 순서

    Date2019.01.05 CategoryQML and Qt Quick By운영자 Views110094
    read more
  2. Windows환경에서 mingw로 Qt 5.10 정적(static)빌드

    Date2018.02.01 CategoryInstallation and Deployment Bymakersweb Views8261
    Read More
  3. 다국어 지원 어플리케이션 개발

    Date2018.01.27 CategoryGeneral and Desktop Bymakersweb Views5453
    Read More
  4. No Image

    Qt 어플리에이션 전역에 폰트 설정

    Date2018.01.24 CategoryGeneral and Desktop Bymakersweb Views8508
    Read More
  5. Qt 3D Studio 시작하기

    Date2018.01.11 CategoryInstallation and Deployment Bymakersweb Views6265
    Read More
  6. No Image

    QPA 플러그인과 HTML5 Backend

    Date2017.12.27 CategoryMobile and Embedded Bymakersweb Views3711
    Read More
  7. 임의의 메모리 영역(QImage)에 QPainter를 이용하여 그리기

    Date2017.12.19 CategoryGeneral and Desktop Bymakersweb Views6552
    Read More
  8. No Image

    QML에서 undefined를 확인하는 방법

    Date2017.11.29 CategoryQML and Qt Quick Bymakersweb Views4376
    Read More
  9. QPA 플러그인과 EGLFS

    Date2017.11.21 CategoryMobile and Embedded Bymakersweb Views7326
    Read More
  10. No Image

    타임스탬프( timestamp) 유닉스 시간

    Date2017.10.19 CategoryGeneral and Desktop Bymakersweb Views4697
    Read More
  11. No Image

    Qt Logging Rule, Qt 프레임워크 로그 출력

    Date2017.01.13 CategoryGeneral and Desktop Bymakersweb Views7331
    Read More
  12. No Image

    QString 문자열에서 숫자만 추출해서 QString으로 반환

    Date2017.01.10 Bymakersweb Views6061
    Read More
  13. No Image

    멀티 스레드환경, 스레드에 안전한 이벤트처리

    Date2016.10.27 CategoryGeneral and Desktop Bymakersweb Views7713
    Read More
  14. Ubuntu Linux에서 Qt Creator 설치

    Date2016.03.06 CategoryInstallation and Deployment Bymakersweb Views13849
    Read More
  15. QtConcurrent를 이용하여 쓰레드를 만드는 방법과 MapReduce

    Date2016.01.24 Bymakersweb Views12264
    Read More
  16. No Image

    Qt 프로그래밍의 시작

    Date2015.10.25 CategoryGeneral and Desktop Bymakersweb Views17918
    Read More
  17. No Image

    Qt의 스레드간 시그널 슬롯의 커넥션타입

    Date2015.10.24 CategoryGeneral and Desktop Bymakersweb Views13767
    Read More
  18. Qt의 시그널 슬롯 시스템

    Date2015.10.20 CategoryGeneral and Desktop Bymakersweb Views27673
    Read More
  19. No Image

    QQuickImageProvider 를 이용한 Qml 에서 이미지 표시

    Date2015.10.18 CategoryC++ Class Bymakersweb Views8567
    Read More
  20. Qml 사용자 ScrollBar 구현

    Date2015.07.24 CategoryQML and Qt Quick Bymakersweb Views8688
    Read More
  21. No Image

    z-order 를 컨트롤 하기위한 방법

    Date2015.05.13 CategoryQML and Qt Quick Bymakersweb Views9657
    Read More
Board Pagination Prev 1 ... 5 6 7 8 9 Next
/ 9