한국어
Qt
 

C++ Class QThread 및 QMutex 예제

makersweb 2021.01.12 21:25 조회 수 : 5763

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

#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 118389
120 QOpenGLWidget 을 투명하게 적용 file makersweb 2020.02.05 5608
119 MCU용 Qt에 대해서 makersweb 2019.08.22 5628
118 최초의 Qt 6.0 스냅샷 제공 (First Qt 6.0 Snapshot Available) j2doll 2020.06.21 5669
117 Q_D매크로와 d-pointer file makersweb 2019.05.07 5671
116 Qbs에 대한 소개와 설치하는 방법 makersweb 2019.10.09 5719
115 웹기반 Qt Design Viewer [2] file makersweb 2019.10.23 5731
» QThread 및 QMutex 예제 makersweb 2021.01.12 5763
113 Qt3D의 QML 타입으로 3D렌더링 file makersweb 2019.11.20 5802
112 QPA 플러그인과 HTML5 Backend file makersweb 2017.12.27 5838
111 clazy 로 13개의 시그널, 슬롯 오류 해결 makersweb 2022.08.23 5858
110 Loader를 사용하여 동적으로 QML 로드 makersweb 2021.01.19 5873
109 컨테이너에 적재된 객체를 편리하게 삭제하기 makersweb 2019.09.18 5888
108 VTK 를 사용해서 강력한 시각화(3D, Plotting, Chart)Qt 응용프로그램 개발하기 file makersweb 2022.10.16 5904
107 Qt5기반 독립 프로세스(out-of-process)로 동작하는 가상키보드(virtual keyboard) file makersweb 2019.02.24 5967
106 [Qt] Google Play의 향후 요구 사항을 준수하는 방법 [2] j2doll 2019.07.29 6054
105 Base64로 인코딩된 파일을 복원 makersweb 2023.08.06 6117
104 Qt MQTT의 pus/sub 튜토리얼 file makersweb 2021.02.06 6140
103 QOpenVirtualkeyboard(Qt 5용 한글 및 영문, 숫자 가상키보드) file makersweb 2019.11.27 6171
102 QML의 사용자 정의 Image makersweb 2023.09.17 6173
101 QML과 JavaScript 의 숫자 관련 내장된 함수 makersweb 2021.03.28 6179