테스트 환경
Windows10 / C++ / Qt 5.15.2 / Qt Creator 4.13.3
목적
Qt Creator를 활용하여 스레드를 사용한다.
Thread 사용
Thread 생성
프로젝트를 우클릭하고 Add new를 선택한다.

New File 창이 뜨면 C++ Class를 선택한다.

Class name을 thread로 지정하면 Header file과 Source file은 자동으로 지정된다.
클래스 이름을 꼭 thread로 지정할 필요는 없으나 아래 예시를 따라가려면 thread로 하는것이 편하다.

프로젝트 트리에 thread.h와 thread.cpp가 추가된다. 만약 자동으로 추가되지 않으면 프로젝트를 우클릭 후 Add Existing Files로 파일을 직접 추가한다.

thread.h
thread.h 파일의 내용을 아래와 같이 수정한다.
#ifndef THREAD_H
#define THREAD_H
#include <QThread>
#include <QtDebug>
class Thread : public QThread
{
Q_OBJECT
public:
explicit Thread(QObject *parent = 0);
private:
void run();
};
#endif // THREAD_H
위 코드에서 선언된 run 함수가 MainWindow에서 호출되어 스레드로 동작하는 함수다.
thread.cpp
thread.cpp 파일의 내용을 아래와 같이 수정한다.
#include "thread.h"
Thread::Thread(QObject *parent) :
QThread(parent)
{
}
void Thread::run()
{
while(1)
{
qDebug() << "thread";
}
}
생성된 스레드는 “thread”를 무한히 출력한다.
mainwindow.h
mainwindow.h 파일을 아래와 같이 수정한다.
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include "ui_mainwindow.h"
#include "thread.h"
#include <QMainWindow>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
Thread *thread;
};
#endif // MAINWINDOW_H
mainwindow.cpp
mainwindow.cpp를 아래와 같이 수정한다.
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
thread = new Thread(this);
thread->start();
while(1)
{
qDebug() << "mainwindow";
}
}
MainWindow::~MainWindow()
{
delete ui;
}
위 코드는 스레드의 스타트 함수(thread->start())가 MainWindow 함수에 있기 때문에 프로그램 실행과 동시에 스레드가 실행된다.
위 코드를 실행하면 mainwindow와 thread가 번갈아가며 출력된다.
