我想写一些必须在自己的线程中工作的类。我读过这篇文章: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 of TestClass中,我放置了所有的初始化过程。1.我可以moveToThread in TestClass的构造函数吗?比如:
TestClass::TestClass() {
QThread *thread = new QThread();
this->moveToThread(thread);
thread->start();
QObject::connect(thread, SIGNAL(started()), this, SLOT(start()));
}之后,该类的所有对象都将在自己的线程中工作。
TestClass中,我有私有struct,可以在两个线程中进行更改。我应该为此使用mutex还是使用信号/插槽:
void::changeStruct(Int newValue) { //主线程中调用的线程发出此->changeValue( newValue);} //槽式空测试类::changeStructSlot(Int NewValue){ //此插槽将在第二个线程this._struct.val =newValue}中调用;发布于 2016-03-01 17:38:59
TestClass应该做的事情之上,您尝试添加内部线程管理。另外,由于线程管理,TestClass析构函数将变得有点复杂。TestClass对象都有自己的struct。如果主线程的调用是更改val的唯一方法,那么就不需要做什么了。如果val可以从多个线程(包括它自己的线程)更改,那么使用QMutex。https://stackoverflow.com/questions/35728160
复制相似问题