한국어
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 QPA 플러그인과 HTML5 Backend file makersweb 2017.12.27 809
138 QML에서 Websocket 서버와 통신 file makersweb 2021.09.18 834
137 Qt 6의 C++ 프로퍼티 바인딩 예제 makersweb 2021.11.01 857
136 Qt로 작성된 iOS 앱에서 시리얼 통신 file makersweb 2022.04.30 867
135 Qt 응용프로그램에서 Lottie Animation사용 file makersweb 2021.05.30 885
134 Qt로 작성된 안드로이드 APP에 Splash Screen을 추가 file makersweb 2020.03.10 885
133 QML 에서 QR코드 생성 file makersweb 2021.08.20 897
132 QML 바인딩 끊김 진단 makersweb 2020.11.08 915
131 Qt 5 코드를 Qt 6로 포팅하기 위해 도움이 되는 Clazy Framework file makersweb 2021.03.01 925
130 Qt 5.15 및 Qt 6의 출시 일정 makersweb 2020.04.09 934
129 QProcess 예제 (프로그램 재시작) file makersweb 2023.01.25 947
128 Qt MQTT 에 대해서 file makersweb 2020.06.02 962
127 Qt 6.0의 개발 호스트 및 대상 플랫폼 makersweb 2020.09.16 977
126 [Qt] Google Play의 향후 요구 사항을 준수하는 방법 [2] j2doll 2019.07.29 978
125 Qt기반의 서버와 클라이언트간 SOAP(Simple Object Access Protocol) file makersweb 2020.05.11 978
124 Qt로 XML 파싱 : Qt 6에서 업데이트된 (Parsing XML with Qt: Updates for Qt 6) [1] j2doll 2020.01.16 981
123 Qt 6에서 QList 변경사항 makersweb 2020.10.08 989
122 QMake 프로젝트를 CMake 프로젝트로 변환 with qmake2cmake makersweb 2022.09.17 1025
121 QScopedPointer 소개 및 사용법 makersweb 2019.11.29 1033
120 Qt 하이브리드 애플리케이션(Hybrid App) 개발 file makersweb 2023.02.08 1033