Why is it that, for the code below, the Thread1.printEvent() gets printed as often as Thread2.printEvent()? My thought is that since it's 2 separate event loops (due to 2 threads), Thread1.printEvent() should keep on going even though Thread2.printEvent() takes a long time?

Here's how everything is connected:

--> denotes is connected to

Thread1.timer.timeout() --> Thread1.doSomething(); // times out every 1 second
Thread1.doSomething() --> Thread1.printEvent(); // takes "zero" time
Thread1.doSomething() --> Thread2.printEvent(); // takes 10 seconds


This is the code for Thread1
Qt Code:
  1. #include <QThread>
  2. #include <QTimer>
  3.  
  4. class Thread1 : public QThread
  5. {
  6. Q_OBJECT
  7.  
  8. public:
  9. void run();
  10.  
  11. private:
  12. QTimer* timer;
  13.  
  14. signals:
  15. void doSomething();
  16.  
  17. private slots:
  18. void printEvent();
  19.  
  20. private:
  21. int number;
  22. };
  23.  
  24. #include <iostream>
  25.  
  26. void Thread1::run()
  27. {
  28. number = 0;
  29.  
  30. // We create QTimer here because it has thread-affinity
  31. timer = new QTimer();
  32. if(!QObject::connect( timer,
  33. SIGNAL(timeout()),
  34. this,
  35. SIGNAL(doSomething())))
  36. {
  37. throw std::runtime_error( "ERROR!" );
  38. }
  39. if(!QObject::connect( this,
  40. SIGNAL(doSomething()),
  41. this,
  42. SLOT(printEvent())))
  43. {
  44. throw std::runtime_error( "ERROR!" );
  45. }
  46.  
  47. timer->start(1000);
  48. this->exec();
  49.  
  50. delete timer;
  51. }
  52.  
  53. void Thread1::printEvent()
  54. {
  55. std::cout << "Thread1: sending event... " << number++ << std::endl;
  56. }
To copy to clipboard, switch view to plain text mode 

This is the code for Thread2..
Qt Code:
  1. #include <QThread>
  2.  
  3. class Thread2 : public QThread
  4. {
  5. Q_OBJECT
  6.  
  7. public:
  8. void run();
  9.  
  10. public slots:
  11. void printEvent();
  12.  
  13. private:
  14. int number;
  15. };
  16.  
  17. #include <iostream>
  18.  
  19. void Thread2::run()
  20. {
  21. number = 0;
  22. exec();
  23. }
  24.  
  25. void Thread2::printEvent()
  26. {
  27. std::cout << "Thread2: Received event... " << number++ << std::endl;
  28. if( number < 3 )
  29. {
  30. msleep(10000);
  31. }
  32. }
To copy to clipboard, switch view to plain text mode 

Lastly, this is the code for main.cpp
Qt Code:
  1. #include <QObject>
  2. #include <QtCore/QCoreApplication>
  3.  
  4. int main( int argc,
  5. char* argv[] )
  6. {
  7. argv );
  8.  
  9. Thread1 thread1;
  10. Thread2 thread2;
  11.  
  12. // Connect the 2 threads signal slot here
  13. if (!QObject::connect(&thread1, SIGNAL(doSomething()),
  14. &thread2, SLOT(printEvent())))
  15. {
  16. throw std::runtime_error( "ERROR!" );
  17. }
  18.  
  19. thread1.start();
  20. thread2.start();
  21.  
  22. return a.exec();
  23. }
To copy to clipboard, switch view to plain text mode