Hello guys I’m learning Qt and I’ve reached QThread class. Having no experience in multithreading I spent several hours studying semaphores, mutexes, critical sections and wait functions in Win32API. When I launched several threads there and the ++ or — a global variable without synchronization I got different results each time. Now I am trying to do the same with QThread but I am getting failed. Can you tell me what’s wrong? here is my code:
#include <QCoreApplication>
#include <QMutex>
#include <QSemaphore>
#include <QThread>
#include <cstdio>
static const int N = 2000000;
class Thread : public QThread {
public:
Thread();
void run();
private:
static QMutex mutex;
};
QMutex Thread::mutex;
static int g_counter = 0;
int main(int argc, char *argv[]) {
QCoreApplication app(argc, argv);
Thread A, B, C;
A.run();
B.run();
C.run();
char c;
scanf("%c", &c);
printf("%d\n", g_counter);
return app.exec();
}
Thread::Thread() {
}
void Thread::run() {
//QMutexLocker lock(&mutex);
for (int i = 0; i < N; ++i) {
++g_counter;
--g_counter;
}
}
I expected to see g_counter jumping up and down as three threads are changing it at the same time. My problem was that I used run() so it executed as a simple function instead of start() to launch it as a thread. Anyway thanks.
I’m not sure what you are trying to do here, but you need to start the thread by calling start(). You also need to lock the mutex, otherwise what’s the point?