A QThread object manages one thread of control within the program. QThreads begin executing in run(). By default, run() starts the event loop by calling exec() and runs a Qt event loop inside the thread. You can use worker objects by moving them to the thread using QObject::moveToThread().
The purpose of a QMutex is to protect an object, data structure or section of code so that only one thread can access it at a time (this is similar to the Java synchronized keyword). It is usually best to use a mutex with a QMutexLocker since this makes it easy to ensure that locking and unlocking are performed consistently.
아래의 소스는 Qt 프레임워크에서 Thread를 다루는 기본적인 예제이다. QMutex를 사용하여 Thread 동기화, Qt에서 Thread 사용을 위한 올바른 방법 그리고 UI(예, Label, Button 2개)에서 QThread를 사용하는 방법을 살펴본다.
QT의 핵심기능 중 하나인 Signal, Slot은 객체 간의 통신에 사용된다. 일반적인 개발언어의 객체 간 메시지 통신인 ‘메시지-메시지 핸들러’, ‘이벤트-이벤트 핸들러’와 유사한 개념이다. signal과 slot을 연결하기 위해 connect()를 사용한다. connect를 사용하는 방법은 함수 포인터를 사용하거나 람다에 연결한다. Singleton으로 확장한 예제는 여기(GitHub)에서 볼 수 있다.
connect(sender, &QObject::destroyed, this, &MyObject::objectDestroyed);
connect(sender, &QObject::destroyed, this, [=](){this->m_objects.remove(sender);});
//main.cpp
#include "water_cooler.h"
#include <QCoreApplication>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
WaterCooler Cooler;
a.exit(0);
}
QT/C++ 개발환경에서 디버그 메시지(로깅)를 파일로 저장해보는 예제이다. qDebug(), qInfo(), qWarning(), qCritical(), qFatal() 매크로를 사용하고 윈도우 환경에서 OutputDebugString 모니터링을 위해 사용한 툴은 여기에서 다운로드한다.
// logwriter.h
#ifndef LOGWRITER_H
#define LOGWRITER_H
#include <QCoreApplication>
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QLoggingCategory>
#include <QScopedPointer>
#include <QTextStream>
class LogWriter {
public:
LogWriter();
~LogWriter();
static QScopedPointer<QFile> m_logFile;
static void WriteLog();
static void MessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg);
};
#endif // LOGWRITER_H