Results 1 to 2 of 2

Thread: Trying to get problems with QThread

  1. #1
    valdemar593 Guest

    Question Trying to get problems with QThread

    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 

  2. #2
    Join Date
    Oct 2010
    Posts
    55
    Thanks
    1
    Thanked 11 Times in 10 Posts
    Qt products
    Qt4
    Platforms
    MacOS X Unix/X11 Windows
    Wiki edits
    9

    Default Re: Trying to get problems with QThread

    First of all, you should call QThread::start() on the threads.

Similar Threads

  1. Problems with a QThread
    By franco.amato in forum Qt Programming
    Replies: 10
    Last Post: 5th April 2010, 10:46
  2. Problems with Qsemaphore and QThread
    By perseo in forum Qt Programming
    Replies: 2
    Last Post: 27th August 2008, 01:21
  3. Replies: 4
    Last Post: 26th June 2008, 18:41
  4. Spawn a QThread in another QThread
    By david.corinex in forum Qt Programming
    Replies: 2
    Last Post: 19th December 2007, 12:54
  5. Problems with QThread and QTcpSocket
    By cookiem in forum Qt Programming
    Replies: 6
    Last Post: 2nd November 2006, 08:25

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.