我想编写一些必须在自己的线程中工作的类。
我读过这篇文章: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()));
在TestClass的slot
中,我放了所有初始化过程。
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;
}
答案 0 :(得分:1)
至少从设计的角度来看,我不会这样做。除了TestClass
应该做的事情之外,您还尝试添加内部线程管理。由于线程管理,TestClass
析构函数也会有点复杂。
每个TestClass
对象都有自己的struct
。如果来自主线程的调用是更改val
的唯一方法,则无需执行任何操作。如果val
可以从多个线程(包括自己的线程)更改,请使用QMutex
。