한국어
Qt
 

C++ Class QThread 및 QMutex 예제

makersweb 2021.01.12 21:25 조회 수 : 1346

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

#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 85854
158 Qt 6.4에 추가될 Qt Quick 3D Physics file makersweb 2022.08.07 343
157 HTTPS URL을 연결할 때 SslHandshakeFailedError 오류 makersweb 2022.07.31 355
156 단일 인스턴스 Qt 응용 프로그램(Single-instance Application) makersweb 2022.06.23 700
155 Qt로 작성된 iOS 앱에서 시리얼 통신 file makersweb 2022.04.30 846
154 VirtualKeyboard 스타일 커스터 마이징 makersweb 2022.03.13 462
153 성능 고려 및 제안 사항 makersweb 2022.03.07 505
152 Binding 타입으로 객체 속성 간 묶기 makersweb 2022.03.04 420
151 Qt Bluetooth Low Energy 개요 makersweb 2022.02.13 661
150 Qt Android 앱에 AdMob 배너달기 file makersweb 2021.12.04 391
149 Qt 6의 C++ 프로퍼티 바인딩 예제 makersweb 2021.11.01 854
148 QML에서 앵커(anchors)로 위치 지정 file makersweb 2021.10.05 3788
147 안드로이드용 Qt 6.2 makersweb 2021.10.02 504
146 Qt 응용프로그램에서 PDF 문서 렌더링 file makersweb 2021.09.23 677
145 QML에서 Websocket 서버와 통신 file makersweb 2021.09.18 826
144 QML 코딩 규칙 makersweb 2021.09.05 3230
143 QML 에서 QR코드 생성 file makersweb 2021.08.20 892
142 앱을 종료할 때 QML 바인딩 오류를 피하는 방법 makersweb 2021.08.08 498
141 Qt 응용프로그램에서 Lottie Animation사용 file makersweb 2021.05.30 881
140 싱글 샷(Single-Shot) 시그널/슬롯 연결 makersweb 2021.05.12 750
139 응용프로그램 자동실행 설정 (on Windows) makersweb 2021.05.08 563