한국어
Qt
 

C++ Class QThread 및 QMutex 예제

makersweb 2021.01.12 21:25 조회 수 : 1416

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

#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 86887
119 Qt로 데이터를 직렬화(serialization)하는 방법 makersweb 2020.08.04 2176
118 최초의 Qt 6.0 스냅샷 제공 (First Qt 6.0 Snapshot Available) j2doll 2020.06.21 643
117 Qt MQTT 에 대해서 file makersweb 2020.06.02 1013
116 Embedded Linux 에서 Qt 및 Graphics Stack file 운영자 2020.05.27 676
115 ShaderEffect QML Type을 이용한 버튼 클릭 효과 file makersweb 2020.05.22 1135
114 Qt기반의 서버와 클라이언트간 SOAP(Simple Object Access Protocol) file makersweb 2020.05.11 1008
113 재진입(Reentrancy) 및 스레드 안전성(Thread-Safety) makersweb 2020.04.19 1281
112 Qt 5.15 및 Qt 6의 출시 일정 makersweb 2020.04.09 964
111 콘솔에서 사용자 입력받기 file makersweb 2020.03.22 51921
110 컨테이너 클래스 - QVector makersweb 2020.03.17 2955
109 Qt로 작성된 안드로이드 APP에 Splash Screen을 추가 file makersweb 2020.03.10 930
108 QLabel의 텍스트 색과 배경색을 변경 makersweb 2020.02.25 6853
107 라즈베리파이4에 대한 Qt 5.14.1 크로스컴파일 [1] file makersweb 2020.02.12 4523
106 QOpenGLWidget 을 투명하게 적용 file makersweb 2020.02.05 1107
105 2020년에 변경되는 Qt 오퍼 (Qt offering changes 2020) [2] j2doll 2020.01.31 757
104 Qt로 XML 파싱 : Qt 6에서 업데이트된 (Parsing XML with Qt: Updates for Qt 6) [1] j2doll 2020.01.16 1018
103 Qt 멀티 스레드 프로그래밍 시 유의해야 할 몇 가지 makersweb 2020.01.13 5019
102 ApplicationWindow 와 메뉴바(MenuBar)구성 file makersweb 2020.01.04 1554
101 QThread 소개 및 예제 makersweb 2019.12.25 19886
100 Qt의 오픈소스 라이센스 소개 file makersweb 2019.12.15 12825