한국어
Qt
 

C++ Class QThread 및 QMutex 예제

makersweb 2021.01.12 21:25 조회 수 : 1419

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

#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 86898
59 Windows에서 Qt D-Bus를 사용하여 프로세스간 통신(IPC) file makersweb 2019.05.02 4599
58 QML과 QtQuick 모듈 개념과 기본 타입들 makersweb 2019.04.26 13548
57 QML 전역 객체 (Global Object) file makersweb 2019.04.10 1116
56 tslib의 ts_calibrate를 응용해서 Qt로 터치보정기능 구현 file makersweb 2019.04.06 1420
55 GPU가 없는 장치에서 Qt Quick을 사용 makersweb 2019.04.02 1921
54 QTextCodec클래스를 사용하여 유니코드와 EUC-KR 변환 makersweb 2019.03.25 2980
53 qInstallMessageHandler를 이용한 디버그 메세지 출력 제어하기 makersweb 2019.02.25 1416
52 Qt5기반 독립 프로세스(out-of-process)로 동작하는 가상키보드(virtual keyboard) file makersweb 2019.02.24 2686
51 Qml 기본 컴포넌트 강좌 (4) - 모델 리스팅(Listing) file 운영자 2019.02.23 5414
50 Qt Bluetooth를 이용한 시리얼(Serial) 통신 file makersweb 2019.02.17 3685
49 Qml 기본 컴포넌트 강좌 (3) - 배치(positioning) 컴포넌트 file 운영자 2019.02.10 4984
48 QString 문자열 다루기 예제 운영자 2019.01.26 40983
47 Qt SQL을 이용한 가벼운 데이터베이스 다루기 [1] file 운영자 2019.01.23 7116
46 구글 클라우드 Speech-To-Text API를 Qt기반(C++, Qml)테스트 [7] file makersweb 2019.01.20 2700
45 QNetworkAccessManager를 통해 HTTP POST 하는 예제 makersweb 2019.01.17 4887
44 Qt응용프로그램 실행 시 콘솔창(터미널)같이 띄우기 file makersweb 2019.01.16 4587
43 안드로이드 가상장치 사용 file makersweb 2019.01.13 1133
42 Qml 기본 컴포넌트 강좌 (2) [2] file makersweb 2019.01.05 8759
41 Qml 기본 컴포넌트 강좌 (1) file makersweb 2019.01.03 12277
40 QtWayland와 ivi-compositor file makersweb 2018.12.27 2473