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
TestClass
I have privatestruct
which can be changed in both threads. Should I usemutex
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; }