Hi,

I'm new to Qt and threading, so I'm probably missing something obvious. I'm trying to use a thread in my application (subclassing QThread), and everything seems to be working. However, when the thread goes into a time consuming operation, my whole GUI freezes up.

I have created a simplified version which is available at http://dsarkar.fhcrc.org/qtthread/. Basically, the main thread and the secondary thread both start a timer (1 and 2 seconds each) that print a message to the console when they timeout(). When I start the application, both sets of messages are printed as expected. There is a menu action that emits a signal that is connected to a slot in the thread making it sleep for 10 seconds. When this is triggered, I would have expected the main thread to keep on going. Instead, both sets of timers stop and the whole GUI freezes up for 10 seconds.

The full code is available on the website. Here are the main parts:

myMainWindow.cpp:

Qt Code:
  1. MyMainWindow::MyMainWindow()
  2. {
  3. createActions();
  4. createMenus();
  5. mythread = new MyThread();
  6. QTimer *timer = new QTimer(this);
  7. connect(timer, SIGNAL(timeout()),
  8. this, SLOT(reportStatus()));
  9. timer->start(2000);
  10. connect(this, SIGNAL(needSleep(unsigned int)),
  11. mythread, SLOT(sleepFor(unsigned int)));
  12. }
  13.  
  14. void MyMainWindow::reportStatus()
  15. {
  16. printf("Main eventloop timeout event\n");
  17. }
  18.  
  19. void MyMainWindow::createActions()
  20. {
  21. sleepAct = new QAction("&Make Thread Sleep", this);
  22. sleepAct->setShortcut(tr("Ctrl+S"));
  23. connect(sleepAct, SIGNAL(triggered()),
  24. this, SLOT(makeThreadSleep()));
  25. }
  26.  
  27.  
  28. void MyMainWindow::makeThreadSleep()
  29. {
  30. emit needSleep(10);
  31. }
To copy to clipboard, switch view to plain text mode 

myThread.cpp:
Qt Code:
  1. #include <unistd.h>
  2.  
  3. MyThread::MyThread(QObject * parent)
  4. : QThread(parent)
  5. {
  6. QTimer *ttimer = new QTimer(this);
  7. connect(ttimer, SIGNAL(timeout()),
  8. this, SLOT(reportThreadStatus()));
  9. ttimer->start(1000);
  10. return;
  11. }
  12.  
  13. void MyThread::reportThreadStatus()
  14. {
  15. printf("Thread eventloop timeout event\n");
  16. }
  17.  
  18. void MyThread::sleepFor(unsigned int t)
  19. {
  20. printf("Thread going to sleep for %d seconds...\n", t);
  21. sleep(t);
  22. printf("Thread waking up...\n");
  23. }
  24.  
  25.  
  26. void MyThread::run()
  27. {
  28. exec();
  29. }
To copy to clipboard, switch view to plain text mode 

main.cpp:

Qt Code:
  1. int main(int argc, char *argv[])
  2. {
  3. QApplication app(argc, argv);
  4. MyMainWindow mainWin;
  5. mainWin.show();
  6. mainWin.mythread->start();
  7. return app.exec();
  8. }
To copy to clipboard, switch view to plain text mode 

Does anyone see what I'm doing wrong? Thanks,
-Deepayan