한국어
Qt
 

C++ Class QThread 및 QMutex 예제

makersweb 2021.01.12 21:25 조회 수 : 1357

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

#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 86122
139 멀티 스레드환경, 스레드에 안전한 이벤트처리 makersweb 2016.10.27 5037
138 C++로 구현된 모델을 QML의 ListView에서 참조 file makersweb 2019.09.07 4933
137 Qml 기본 컴포넌트 강좌 (3) - 배치(positioning) 컴포넌트 file 운영자 2019.02.10 4886
136 Qt 멀티 스레드 프로그래밍 시 유의해야 할 몇 가지 makersweb 2020.01.13 4882
135 QNetworkAccessManager를 통해 HTTP POST 하는 예제 makersweb 2019.01.17 4792
134 Windows에서 Qt D-Bus를 사용하여 프로세스간 통신(IPC) file makersweb 2019.05.02 4499
133 Qt응용프로그램 실행 시 콘솔창(터미널)같이 띄우기 file makersweb 2019.01.16 4497
132 라즈베리파이4에 대한 Qt 5.14.1 크로스컴파일 [1] file makersweb 2020.02.12 4453
131 QML에서 동적으로 텍스트 다국어 처리 file makersweb 2018.11.04 4228
130 Qt기반의 오픈소스 프로젝트들 - 2 운영자 2019.07.21 4016
129 QPA 플러그인과 EGLFS file makersweb 2017.11.21 3935
128 열거형(enum)을 QML에서 사용하는 방법과 문자열(QString)로 얻기 makersweb 2019.08.20 3897
127 QML에서 앵커(anchors)로 위치 지정 file makersweb 2021.10.05 3866
126 Qt 를 사용하거나 기반으로 하는 응용프로그램 file makersweb 2021.01.30 3839
125 Qt 3D Studio 시작하기 file makersweb 2018.01.11 3829
124 Qt Logging Rule, Qt 프레임워크 로그 출력 makersweb 2017.01.13 3709
123 Qml에서 키보드 입력 이벤트 핸들링 file makersweb 2018.08.09 3602
122 Qt Bluetooth를 이용한 시리얼(Serial) 통신 file makersweb 2019.02.17 3585
121 Qt Version확인 방법 makersweb 2018.03.29 3525
120 QML, 이미지, 폰트등을 바이너리 리소스로 만들기 makersweb 2019.06.24 3523