【发布时间】:2016-03-01 16:26:41
【问题描述】:
我想编写一些必须在自己的线程中工作的类。
我读过这篇文章:http://wiki.qt.io/Threads_Events_QObjects。它建议移动必须在自己的线程中工作的对象,例如:
TestClass tst;
QThread *thread = new QThread();
tst.moveToThread(thread);
thread->start();
QObject::connect(thread, SIGNAL(started()), &tst, SLOT(start()));
在 slot 的 TestClass 中,我放置了所有初始化程序。
1. TestClass的构造函数中可以moveToThread吗?喜欢:
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::invoke/QMetaObject::invokeMethod的地方发出该信号。跨度> -
最好在启动线程之前连接
SIGNAL(start()),否则您可能会因竞争条件而丢失信号。
标签: c++ qt qthread qsignalmapper