QThread moveToThread.QThread 中的同步

QThread moveToThread. Synchronization in QThread

本文关键字:QThread 同步 moveToThread      更新时间:2023-10-16

我想写一些必须在自己的线程中工作的类。我读过这篇文章: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,我放置了所有初始化过程。1. 我可以在测试类的构造函数中移动到线程吗?喜欢:

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. 至少从设计的角度来看,我不会这样做。除了TestClass应该做什么之外,您还尝试添加内部线程管理。此外TestClass析构函数也会因为线程管理而变得有点复杂。

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