한국어
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 임의의 메모리 영역(QImage)에 QPainter를 이용하여 그리기 file makersweb 2017.12.19 3549
118 QML 코딩 규칙 makersweb 2021.09.05 3399
117 qbs 사용 방법(Helloworld) file makersweb 2019.10.23 3138
116 QString 문자열에서 숫자만 추출해서 QString으로 반환 makersweb 2017.01.10 3129
115 다국어 지원 어플리케이션 개발 file makersweb 2018.01.27 3057
114 QTextCodec클래스를 사용하여 유니코드와 EUC-KR 변환 makersweb 2019.03.25 2975
113 컨테이너 클래스 - QVector makersweb 2020.03.17 2955
112 UI 폼(Form)작성 시 탭 순서(Tab Order) 설정 file makersweb 2020.08.24 2939
111 QML에서 멀티 스레드(multithreading) 프로그래밍 file makersweb 2019.05.25 2724
110 구글 클라우드 Speech-To-Text API를 Qt기반(C++, Qml)테스트 [7] file makersweb 2019.01.20 2699
109 Qt5기반 독립 프로세스(out-of-process)로 동작하는 가상키보드(virtual keyboard) file makersweb 2019.02.24 2684
108 Qt3D의 QML 타입으로 3D렌더링 file makersweb 2019.11.20 2594
107 리눅스에서 Qt4.8기반 어플리케이션의 한글입력 file makersweb 2018.11.29 2528
106 QtWayland와 ivi-compositor file makersweb 2018.12.27 2471
105 [Qt News] Qt6 Git 개발 초기 단계 시작하기 j2doll 2019.08.02 2391
104 QOpenVirtualkeyboard(Qt 5용 한글 및 영문, 숫자 가상키보드) file makersweb 2019.11.27 2331
103 main함수 명령줄 옵션 해석 makersweb 2020.09.01 2312
102 OpenGL 렌더링을 QtQuick과 통합하는 방법 file makersweb 2019.10.01 2266
101 Qt Creator에서 임베디드 장치로 deploy설정(Custom Process Step) file makersweb 2019.06.15 2252
100 Qt Creator에서 Qt의존성 라이브러리 자동복사하기 file makersweb 2019.10.19 2218