(Qt6 - Advanced) 2. Mutex

Posted by : at

Category : Qt


QMutex

#include <QCoreApplication>
#include <QDebug>
#include <QThread>
#include <QThreadPool>
#include <QMutex>
#include "counter.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QThread::currentThread()->setObjectName("Main");
    QThreadPool* pool = QThreadPool::globalInstance();

    QMutex mutex;
    int value = 0;
    qInfo() << pool->maxThreadCount() << " Threads";

    for(int i = 0; i < 100; i++)
    {
        Counter* c = new Counter(&mutex,&value);
        c->setAutoDelete(true);
        pool->start(c);
    }

    return a.exec();
}
#ifndef COUNTER_H
#define COUNTER_H

#include <QRunnable>
#include <QThread>
#include <QDebug>
#include <QMutex>

class Counter : public QRunnable
{
public:
    Counter(QMutex* mutex,int* value);

    // QRunnable interface
public:
    void run();

private:
    int* m_value;
    QMutex* m_mutex;
};

#endif // COUNTER_H
#include "counter.h"

Counter::Counter(QMutex *mutex, int *value)
{
    m_value = value;
    m_mutex = mutex;
}


void Counter::run()
{
    //Wait until we can do stuff...

    m_mutex->lock(); //We will wait until we can lock!

    //Our code here
    QThread::currentThread()->msleep(50);
    *m_value = *m_value + 1;
    qInfo() << *m_value << QThread::currentThread();

    m_mutex->unlock(); //Other threads can lock
}

QMutexLocker

#include <QCoreApplication>
#include <QDebug>
#include <QThread>
#include <QThreadPool>
#include <QMutex>
#include "counter.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QThread::currentThread()->setObjectName("Main");
    QThreadPool* pool = QThreadPool::globalInstance();

    QMutex mutex;
    int value = 0;

    qInfo() << pool->maxThreadCount() << " Threads";

    for (int i = 0; i < 100; i++)
    {
        Counter* c = new Counter(&mutex, &value);
        c->setAutoDelete(true);
        pool->start(c);
    }

    return a.exec();
}
#ifndef COUNTER_H
#define COUNTER_H

#include <QRunnable>
#include <QThread>
#include <QDebug>
#include <QMutex>
#include <QMutexLocker>

class Counter : public QRunnable
{
public:
    Counter(QMutex* mutex,int* value);

    // QRunnable interface
public:
    void run();

private:
    int* m_value;
    QMutex* m_mutex;
};

#endif // COUNTER_H
#include "counter.h"

Counter::Counter(QMutex *mutex, int *value)
{
    m_value = value;
    m_mutex = mutex;
}


void Counter::run()
{
    //Wait until we can do stuff...


    //Our code here
    QThread::currentThread()->msleep(50);

    QMutexLocker locker(m_mutex);
    *m_value = *m_value + 1;
    qInfo() << *m_value << QThread::currentThread();


}

About Taehyung Kim

안녕하세요? 8년차 현업 C++ 개발자 김태형이라고 합니다. 😁 C/C++을 사랑하며 다양한 사람과의 협업을 즐깁니다. ☕ 꾸준한 자기개발을 미덕이라 생각하며 노력중이며, 제가 얻은 지식을 홈페이지에 정리 중입니다. 좀 더 상세한 제 이력서 혹은 Private 프로젝트 접근 권한을 원하신다면 메일주세요. 😎

Star
Useful Links