首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >QThread moveToThread.QThread中的同步

QThread moveToThread.QThread中的同步
EN

Stack Overflow用户
提问于 2016-03-01 16:26:41
回答 1查看 589关注 0票数 0

我想写一些必须在自己的线程中工作的类。我读过这篇文章:http://wiki.qt.io/Threads_Events_QObjects。它建议移动必须在自己线程中工作的对象,例如:

代码语言:javascript
复制
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的构造函数吗?比如:

代码语言:javascript
复制
TestClass::TestClass() {
  QThread *thread = new QThread();
  this->moveToThread(thread);
  thread->start();  
  QObject::connect(thread, SIGNAL(started()), this, SLOT(start()));
}

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

  1. TestClass中,我有私有struct,可以在两个线程中进行更改。我应该为此使用mutex还是使用信号/插槽: void::changeStruct(Int newValue) { //主线程中调用的线程发出此->changeValue( newValue);} //槽式空测试类::changeStructSlot(Int NewValue){ //此插槽将在第二个线程this._struct.val =newValue}中调用;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-01 17:38:59

  1. 至少从设计的角度来看,我是不会这么做的。在TestClass应该做的事情之上,您尝试添加内部线程管理。另外,由于线程管理,TestClass析构函数将变得有点复杂。
  2. 每个TestClass对象都有自己的struct。如果主线程的调用是更改val的唯一方法,那么就不需要做什么了。如果val可以从多个线程(包括它自己的线程)更改,那么使用QMutex
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35728160

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档