한국어
Qt
 

C++ Class QThread 및 QMutex 예제

makersweb 2021.01.12 21:25 조회 수 : 5487

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

#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 117121
160 QMake 프로젝트를 CMake 프로젝트로 변환 with qmake2cmake makersweb 2022.09.17 4085
159 QML 바인딩 끊김 진단 makersweb 2020.11.08 4098
158 Qt MQTT 에 대해서 file makersweb 2020.06.02 4130
157 단일 인스턴스 Qt 응용 프로그램(Single-instance Application) makersweb 2022.06.23 4150
156 QScopedPointer 소개 및 사용법 makersweb 2019.11.29 4205
155 Embedded Linux 에서 Qt 및 Graphics Stack file 운영자 2020.05.27 4247
154 Qt 5 코드를 Qt 6로 포팅하기 위해 도움이 되는 Clazy Framework file makersweb 2021.03.01 4271
153 QML과 코루틴(Coroutines) makersweb 2020.11.03 4278
152 QRhi 에 대해서 file makersweb 2023.12.29 4279
151 Qt 6에서 QList 변경사항 makersweb 2020.10.08 4293
150 ApplicationWindow 와 메뉴바(MenuBar)구성 file makersweb 2020.01.04 4318
149 Qbs 프로젝트를 정의하기 위해 사용되는 몇가지 중요한 아이템들 file makersweb 2019.10.13 4329
148 하드디스크 드라이브 여유 공간 계산 file makersweb 2023.01.15 4366
147 tslib의 ts_calibrate를 응용해서 Qt로 터치보정기능 구현 file makersweb 2019.04.06 4388
146 안드로이드 가상장치 사용 file makersweb 2019.01.13 4457
145 Qt Bluetooth 관련 기능 확인 사항 makersweb 2018.07.10 4470
144 Qt 6의 C++ 프로퍼티 바인딩 예제 makersweb 2021.11.01 4497
143 ShaderEffect QML Type을 이용한 버튼 클릭 효과 file makersweb 2020.05.22 4526
142 Qt 스마트 포인터 (QSharedPointer, QScopedPointer, QPointer) makersweb 2022.08.18 4553
141 Android 애플리케이션 서명 구성 file makersweb 2023.12.17 4556