I read some article on the Qt dev blog which suggest the proper way to do multithread stuff is to use moveToThread instead of subclassing QThread.

I have this class that does some serious work which i like to run on a separate thread.

So basically the code look something like this:

Qt Code:
  1. .H file
  2. class Data : QObject
  3. {
  4. public:
  5. void update();
  6. };
  7.  
  8. class Worker : QObject
  9. {
  10. public:
  11. void setData( Data* data ) { mData = data; }
  12.  
  13. signals:
  14. void workCompleted();
  15.  
  16. public slots:
  17. void doWork();
  18.  
  19. private:
  20. Data* mData;
  21. };
  22. class Master : QObject
  23. {
  24. Master() { mWorker = new Worker; mWorkerThread = new QThread; }
  25. void askWorkerToWork();
  26.  
  27. private:
  28. Worker* mWorker;
  29. QThread* mWorkerThread;
  30. };
  31.  
  32. .CPP file
  33. void Data::update()
  34. {
  35. UpdateEvent e("Updated");
  36. QCoreApplication::sendEvent(this, &e);
  37. }
  38.  
  39. void Worker::doWork()
  40. {
  41. // run some computation
  42. this->moveToThread(QCoreApplication::instance()->thread());
  43. mData->update();
  44. emit workCompleted();
  45. }
  46.  
  47. void Master::askWorkerToWork()
  48. {
  49. Data* data = new Data;
  50. mWorker->setData(data);
  51. mWorker->moveToThread(mWorkerThread);
  52. connect(mWorkerThread, SIGNAL(started()), mWorker, SLOT(doWork()), Qt::UniqueConnection);
  53. connect(mWorker, SIGNAL(workCompleted()), mWorkerThread, SLOT(quit()), Qt::UniqueConnection);
  54. mWorkerThread->start();
  55. }
To copy to clipboard, switch view to plain text mode 

I would like to know given the above setup does Qt automatically move the mWorker back to thread which Master object is created when the thread quits? Or do I have to do a moveToThread as shown in the code manually?

Does the moveToThread function actually move the object to the target thread immediately? Qt complains that I cannot call the function QCoreApplication::sendEvent in the Data object because it is created on a different thread.