c++qtqthreadqsignalmapper

QThread moveToThread. Synchronization in QThread


I want to write some class which has to work in own thread. I've read this article: http://wiki.qt.io/Threads_Events_QObjects. It advises to move object which has to work in own thread, like:

TestClass tst;
QThread *thread = new QThread();
tst.moveToThread(thread);
thread->start();
QObject::connect(thread, SIGNAL(started()), &tst, SLOT(start()));

And in slot of TestClass I put all initializations procedures. 1. Can I moveToThread in TestClass' constructor? Like:

TestClass::TestClass() {
  QThread *thread = new QThread();
  this->moveToThread(thread);
  thread->start();  
  QObject::connect(thread, SIGNAL(started()), this, SLOT(start()));
}

After that all objects of this class will be working in own threads.

  1. In TestClass I have private struct which can be changed in both threads. Should I use mutex for that or use signal/slots:

    void TestClass::changeStruct(int newValue) {
      // invoked in main thread
    
      emit this->changeValue(newValue);
    
    }
    
    // slot
    void TestClass::changeStructSlot(int newValue) {
      // this slot will be invoked in the second thread
      this._struct.val = newValue;
    }
    

Solution

    1. I wouldn't do it at least from the design point of view. On top of what TestClass is supposed to do you try to add internal thread management. Also TestClass destructor is going to be little bit complicated because of thread management.

    2. Every TestClass object has its own struct. If the call from main thread is the only way to change val then nothing has to be done. If the val can be changed from more than 1 thread including its own then use QMutex.