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:
Qt Code:
  1. #include <QCoreApplication>
  2. #include <QMutex>
  3. #include <QThread>
  4. #include <cstdio>
  5.  
  6. static const int N = 2000000;
  7.  
  8. class Thread : public QThread {
  9. public:
  10. Thread();
  11. void run();
  12. private:
  13. void Inc();
  14. void Dec();
  15. static QMutex mutex;
  16. };
  17.  
  18. QMutex Thread::mutex;
  19. static int g_counter = 0;
  20.  
  21. int main(int argc, char *argv[]) {
  22. QCoreApplication app(argc, argv);
  23. Thread A, B, C;
  24. A.run();
  25. B.run();
  26. C.run();
  27. char c;
  28. scanf("%c", &c);
  29. printf("%d\n", g_counter);
  30. return app.exec();
  31. }
  32.  
  33. Thread::Thread() {
  34.  
  35. }
  36.  
  37. void Thread::run() {
  38. //QMutexLocker lock(&mutex);
  39. for (int i = 0; i < N; ++i) {
  40. ++g_counter;
  41. --g_counter;
  42. }
  43. }
To copy to clipboard, switch view to plain text mode