我想写一些必须在自己的线程工作的类。 我读过这篇文章:http://wiki.qt.io/Threads_Events_QObjects
。它建议移动对象,在自己的线程工作,如:QThread moveToThread。在QThread同步
TestClass tst;
QThread *thread = new QThread();
tst.moveToThread(thread);
thread->start();
QObject::connect(thread, SIGNAL(started()), &tst, SLOT(start()));
而且在识别TestClass的slot
我把所有的初始化程序。 1.我可以在TestClass的构造函数中移动到线程吗?像:
TestClass::TestClass() {
QThread *thread = new QThread();
this->moveToThread(thread);
thread->start();
QObject::connect(thread, SIGNAL(started()), this, SLOT(start()));
}
之后,此类的所有对象将在自己的线程中工作。
在
TestClass
我有私人struct
它可以在两个线程中进行更改。 我应该使用mutex
为或使用信号/时隙: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; }
为什么,仅仅发出信号的功能,为什么不把信号连接到'的TestClass :: changeStructSlot'并发出在那里你调用'的TestClass :: changeStruct'该信号,或致电['QMetaMethod ::调用'](http://doc.qt.io/qt-5/qmetamethod.html#invoke)/ ['QMetaObject :: invokeMethod'](http://doc.qt.io/qt-5/qmetaobject.html #invokeMethod)。 – thuga
在启动线程之前更好地连接'SIGNAL(start())',否则可能会由于竞态条件而丢失信号。 –