QThread moveToThread。 QThread中的同步

时间:2016-03-01 16:26:42

标签: c++ qt qthread qsignalmapper

我想编写一些必须在自己的线程中工作的类。 我读过这篇文章: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()));
}

之后,这个类的所有对象都将在自己的线程中工作。

  1. 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;
    }
    

1 个答案:

答案 0 :(得分:1)

  1. 至少从设计的角度来看,我不会这样做。除了TestClass应该做的事情之外,您还尝试添加内部线程管理。由于线程管理,TestClass析构函数也会有点复杂。

  2. 每个TestClass对象都有自己的struct。如果来自主线程的调用是更改val的唯一方法,则无需执行任何操作。如果val可以从多个线程(包括自己的线程)更改,请使用QMutex