한국어
Qt
 

C++ Class QThread 및 QMutex 예제

makersweb 2021.01.12 21:25 조회 수 : 1424

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

#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 86948
59 Qt Version확인 방법 makersweb 2018.03.29 3632
58 Qt Bluetooth를 이용한 시리얼(Serial) 통신 file makersweb 2019.02.17 3687
57 Qml에서 키보드 입력 이벤트 핸들링 file makersweb 2018.08.09 3707
56 Qt Logging Rule, Qt 프레임워크 로그 출력 makersweb 2017.01.13 3813
55 Qt 3D Studio 시작하기 file makersweb 2018.01.11 3901
54 Qt 를 사용하거나 기반으로 하는 응용프로그램 file makersweb 2021.01.30 3995
53 QPA 플러그인과 EGLFS file makersweb 2017.11.21 4013
52 열거형(enum)을 QML에서 사용하는 방법과 문자열(QString)로 얻기 makersweb 2019.08.20 4028
51 QML에서 앵커(anchors)로 위치 지정 file makersweb 2021.10.05 4074
50 Qt기반의 오픈소스 프로젝트들 - 2 운영자 2019.07.21 4101
49 QML에서 동적으로 텍스트 다국어 처리 file makersweb 2018.11.04 4315
48 라즈베리파이4에 대한 Qt 5.14.1 크로스컴파일 [1] file makersweb 2020.02.12 4530
47 Qt응용프로그램 실행 시 콘솔창(터미널)같이 띄우기 file makersweb 2019.01.16 4591
46 Windows에서 Qt D-Bus를 사용하여 프로세스간 통신(IPC) file makersweb 2019.05.02 4621
45 QNetworkAccessManager를 통해 HTTP POST 하는 예제 makersweb 2019.01.17 4893
44 Qml 기본 컴포넌트 강좌 (3) - 배치(positioning) 컴포넌트 file 운영자 2019.02.10 4994
43 Qt 멀티 스레드 프로그래밍 시 유의해야 할 몇 가지 makersweb 2020.01.13 5038
42 C++로 구현된 모델을 QML의 ListView에서 참조 file makersweb 2019.09.07 5042
41 멀티 스레드환경, 스레드에 안전한 이벤트처리 makersweb 2016.10.27 5205
40 Qml 기본 컴포넌트 강좌 (4) - 모델 리스팅(Listing) file 운영자 2019.02.23 5420