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.
In
TestClassI have privatestructwhich can be changed in both threads. Should I usemutexfor 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; }
I wouldn't do it at least from the design point of view. On top of what
TestClassis supposed to do you try to add internal thread management. AlsoTestClassdestructor is going to be little bit complicated because of thread management.Every
TestClassobject has its ownstruct. If the call from main thread is the only way to changevalthen nothing has to be done. If thevalcan be changed from more than 1 thread including its own then useQMutex.