PDA

View Full Version : Trying to get problems with QThread



valdemar593
21st May 2011, 21:20
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 ++ and -- 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 <QThread>
#include <cstdio>

static const int N = 2000000;

class Thread : public QThread {
public:
Thread();
void run();
private:
void Inc();
void Dec();
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;
}
}

helloworld
21st May 2011, 22:26
First of all, you should call QThread::start() on the threads.