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();
}