본문 바로가기

Programming/QT&QML

[QT, QML] Signal, Slot 동기(synchronous), 비동기(Asynchronous) ynchronous), 비동기(Asynchronous) 작업

728x90
반응형
# QT Version : 5.12 
# QT Creatpr Version : 4.11
# Project name : SignaSlot_Synchronos

My_Github_Link

 

jungmonster/qt_study_project

Qt projects for my study. Contribute to jungmonster/qt_study_project development by creating an account on GitHub.

github.com

Qt에서는 signal, slot을 통해서 간단히 동기(Synchronous), 비동기(Asynchronous)를 확인할 수 있다.

동기(Synchronous)

간단히 PrintLog, TimerLog 클래스를 만들어 준다.
PrintLog

#include <QObject>
#include <iostream>

using namespace std;

class PrintLog : public QObject
{
    Q_OBJECT
public:
    PrintLog();

    void print_log();
signals:
    void call_ShowLog();
};

PrintLog::PrintLog()
{
}

void PrintLog::print_log()
{
    cout << " print 01 " << endl;
    emit call_ShowLog();
    cout << " print 03 " << endl;
}

TimerLog

#include <QObject>
#include <iostream>
#include <QThread>

using namespace std;

class TimerLog : public QObject
{
    Q_OBJECT
public:
    TimerLog();

public slots:
    void show_log();
};

다음 main에서 PrintLog의 call_Showlog() signal과 TimerLog의 show_log() slot을 연결해준 뒤, PrintLog의 print_log() 함수를 실행해준다.

main

#include <QCoreApplication>

#include "printlog.h"
#include "timerlog.h"
#include <QObject>

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

    PrintLog* print = new PrintLog();
    TimerLog* timer = new TimerLog();

    QObject::connect(print, &PrintLog::call_ShowLog, timer, &TimerLog::show_log);

    print->print_log();

    return a.exec();
}

실행하면 콘솔에서 print 01을 출력 후 3초 뒤에 02와 03을 출력한다.

동작 순서를 보면 아래 그림과 같이 실행되며, 각 인스턴스는 동기(Synchronous)로 동작하는 것을 확인할 수 있다.

즉, PrintLog와 TimerLog는 동기화되어서 동작하는 것으로 확인된다.

비동기(Asynchronous)

비동기(Asynchronous) 동작을 확인하기 위해서 TimerLog Class를 별도의 Thread로 만들어 준다.

다른 코드는 수정 없이 main()만 간단히 수정한다.

Qt에서 Thread 생성 방법 중 movetothread를 이용해서 간단히 TimerLog Class를 thread로 만들어 준다.

#include <QCoreApplication>

#include "printlog.h"
#include "timerlog.h"
#include <QObject>
#include <QThread>

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

    PrintLog* print = new PrintLog();
    TimerLog* timer = new TimerLog();

    QThread* thread = new QThread();

    QObject::connect(print, &PrintLog::call_ShowLog, timer, &TimerLog::show_log);

    timer->moveToThread(thread);
    thread->start();

    print->print_log();

    return a.exec();
}

그럼 아래와 같이 01과 03이 출력되고 3초 뒤 02가 출력된다.

이 경우에는 PrintLog와 TimerLog가 별도의 Thread로 동작하며, 비동기(Asynchronous)로 동작되는 것을 확인할 수 있다.

 
반응형

'Programming > QT&QML' 카테고리의 다른 글

[QT, QML] Pyside2 준비  (0) 2020.05.04
[QT, QML] MVC 패턴으로 구현  (0) 2020.04.13
[QT, QML] Signals Slots 사용하기  (0) 2020.04.12
[QT, QML] QML Component anchor  (0) 2020.04.06
[QT, QML] Translation 사용  (0) 2020.04.03