한국어
Qt
 

C++ Class QThread 및 QMutex 예제

makersweb 2021.01.12 21:25 조회 수 : 1415

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

#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 86882
179 Qt 응용프로그램에 Web 구성 요소를 표시 with Servo file makersweb 2024.04.27 298
178 Qbs 프로젝트를 정의하기 위해 사용되는 몇가지 중요한 아이템들 file makersweb 2019.10.13 330
177 Qt 6.4에 추가될 Qt Quick 3D Physics file makersweb 2022.08.07 393
176 HTTPS URL을 연결할 때 SslHandshakeFailedError 오류 makersweb 2022.07.31 411
175 Qt Android 앱에 AdMob 배너달기 file makersweb 2021.12.04 433
174 그래픽 소프트웨어에서 디자인 내보내기 (Exporting Designs from Graphics Software) j2doll 2020.12.25 438
173 Binding 타입으로 객체 속성 간 묶기 makersweb 2022.03.04 471
172 Qt Quick Controls 2에 네이티브 데스크탑 스타일 추가 file makersweb 2020.11.23 526
171 Qt Creator 에서 GitHub Copilot 사용하기 file makersweb 2024.04.13 536
170 VirtualKeyboard 스타일 커스터 마이징 makersweb 2022.03.13 537
169 앱을 종료할 때 QML 바인딩 오류를 피하는 방법 makersweb 2021.08.08 547
168 안드로이드용 Qt 6.2 makersweb 2021.10.02 555
167 성능 고려 및 제안 사항 makersweb 2022.03.07 564
166 Base64로 인코딩된 파일을 복원 makersweb 2023.08.06 574
165 QtQuick 애플리케이션에 Rive 애니메이션 통합 makersweb 2024.03.31 597
164 Qt Safe Renderer 개요 file makersweb 2022.09.08 598
163 응용프로그램 자동실행 설정 (on Windows) makersweb 2021.05.08 609
162 QML과 코루틴(Coroutines) makersweb 2020.11.03 625
161 하드디스크 드라이브 여유 공간 계산 file makersweb 2023.01.15 630
160 clazy 로 13개의 시그널, 슬롯 오류 해결 makersweb 2022.08.23 639