한국어
Qt
 

C++ Class QThread 및 QMutex 예제

makersweb 2021.01.12 21:25 조회 수 : 1358

멀티 스레드에서 공유 리소스에 대한 동시 액세스로 인해 경합이 발생할 수 있다. 다음은 멀티스레드에서 안전하지 않은 전형적인 예를 보여준다. 

#include <QThread>

class Thread : public QThread
{
    bool m_cancel;
public:
    explicit Thread(QObject *parent = nullptr)
        : QThread(parent), m_cancel(false) {}
    
    void cancel() // called by GUI
    {
        m_cancel = true;
    }
    
private:
    bool isCanceled() const // called by run()
    {
        return m_cancel;
    }
    
    void run() override { // reimplemented from QThread
        while (!isCanceled())
            doSomething();
    }
};

 

다음은 QMutex 를 사용하여 스레드를 동기화는 방법을 보여준다.

#include <QThread>

class Thread : public QThread
{
    mutable QMutex m_mutex; // protects m_cancel
    bool m_cancel;
public:
    explicit Thread(QObject *parent = nullptr)
        : QThread(parent), m_cancel(false) {}
    
    void cancel() { // called by GUI
        const QMutexLocker locker(&m_mutex);
        m_cancel = true;
    }
    
private:
    bool isCanceled() const { // called by run()
        const QMutexLocker locker(&m_mutex);
        return m_cancel;
    }
    
    void run() override { // reimplemented from QThread
        while (!isCanceled())
            doSomething();
    }
};

 

번호 제목 글쓴이 날짜 조회 수
공지 Qt프로그래밍(QtQuick) Beginner를 위한 글 읽는 순서 운영자 2019.01.05 86178
139 Qml 기본 컴포넌트 강좌 (1) file makersweb 2019.01.03 12121
138 Qml 기본 컴포넌트 강좌 (2) [2] file makersweb 2019.01.05 8654
137 안드로이드 가상장치 사용 file makersweb 2019.01.13 1074
136 Qt응용프로그램 실행 시 콘솔창(터미널)같이 띄우기 file makersweb 2019.01.16 4502
135 QNetworkAccessManager를 통해 HTTP POST 하는 예제 makersweb 2019.01.17 4801
134 구글 클라우드 Speech-To-Text API를 Qt기반(C++, Qml)테스트 [7] file makersweb 2019.01.20 2624
133 Qt SQL을 이용한 가벼운 데이터베이스 다루기 [1] file 운영자 2019.01.23 6995
132 QString 문자열 다루기 예제 운영자 2019.01.26 40345
131 Qml 기본 컴포넌트 강좌 (3) - 배치(positioning) 컴포넌트 file 운영자 2019.02.10 4890
130 Qt Bluetooth를 이용한 시리얼(Serial) 통신 file makersweb 2019.02.17 3601
129 Qml 기본 컴포넌트 강좌 (4) - 모델 리스팅(Listing) file 운영자 2019.02.23 5325
128 Qt5기반 독립 프로세스(out-of-process)로 동작하는 가상키보드(virtual keyboard) file makersweb 2019.02.24 2632
127 qInstallMessageHandler를 이용한 디버그 메세지 출력 제어하기 makersweb 2019.02.25 1363
126 QTextCodec클래스를 사용하여 유니코드와 EUC-KR 변환 makersweb 2019.03.25 2908
125 GPU가 없는 장치에서 Qt Quick을 사용 makersweb 2019.04.02 1858
124 tslib의 ts_calibrate를 응용해서 Qt로 터치보정기능 구현 file makersweb 2019.04.06 1370
123 QML 전역 객체 (Global Object) file makersweb 2019.04.10 1056
122 QML과 QtQuick 모듈 개념과 기본 타입들 makersweb 2019.04.26 13439
121 Windows에서 Qt D-Bus를 사용하여 프로세스간 통신(IPC) file makersweb 2019.05.02 4510
120 가상키보드(Qt Virtual Keyboard)를 사용하는 방법 [32] file makersweb 2019.05.03 221871