c++ - 同步 QThreads 时出现问题

标签 c++ multithreading qt

除了主线程,我还有 ThinkerThread 对象 _thinker,它的 finished() 信号连接到主线程的槽:

connect(&_thinker, SIGNAL(finished()), this, SLOT(autoMove()));

插槽 autoMove() 导致 _thinker 初始化并再次运行:

_thinker.setState(/* set internal variables to run properly */);
_thinker.start();

这样 _thinker 可以继续运行新数据并在主线程中使用 autoMove() 槽向用户提供一些反馈。

问题是当用户希望为 _thinker 加载新状态(可能来自文件或其他菜单操作)时,我无法同步 _thinker 的两个状态。

假设 _thinker 正在运行,并且用户从文件加载新状态。现在,当 _thinker finished() 时,它将调用 autoMove() 并显示反馈。但是有可能向用户提供了错误的反馈,因为从文件加载可能会导致内部状态发生变化。也就是说,_thinker 的内部状态和主线程的内部状态是不一样的。

  1. _thinker 开始,状态说,s0。
  2. 用户从文件加载另一个状态,比如 s1。
  3. _thinker 完成并执行 autoMove()。

所以在步骤 3 之后,autoMove() 将对状态 s0 进行反馈,这不是预期的。我想要做的是在用户从文件加载新状态时停止执行 _thinker。我认为我的设计很差,我想知道这种情况下的最佳实践。我的加载函数以与 autoMove() 相同的方式初始化 _thinker,调用相同的函数(还有另一个调用 _thinker.setState() 和 start() 的函数)。

现在我在 load() 函数中完成了以下操作:

disconnect(&_thinker, SIGNAL(finished()), this, SLOT(autoMove()));
_thinker.terminate();
_thinker.wait();
connect(&_thinker, SIGNAL(finished()), this, SLOT(autoMove()));

这并没有完全消除问题,即 autoMove() 仍然被调用并给出先前状态的反馈。我在 Windows 中使用 Qt Creator 1.2.1 和 Qt 版本 4.5.2。

感谢您的宝贵时间。

编辑

这是通常的执行步骤(未调用 load() 时):

_thinker.setState();
_thinker.start();
//when _thinker finished()
autoMove();
    > _thinker.setState();
    > _thinker.start();

当 load() 被调用时:

_thinker.setState();
_thinker.start();
load();
    > _thinker.setState();
    > _thinker.start();
//when _thinker finished()
autoMove(); // this is the feedback for previous or current state
    > _thinker.setState();
    > _thinker.start();

请注意,load() 会导致 _thinker 重新启动。现在,在哪里进行 bool 检查,以便 autoMove() 只应忽略一次?

最佳答案

如何使用整数 id 来确定哪个状态已被计算,以查看在计算完成时它是否仍然有效?

关于c++ - 同步 QThreads 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1362674/

相关文章:

c++ - 自动矢量化 GCC

c++ - 这是在 C++ 中释放指针内存的正确方法吗

c++ - 如何重新缩放图像并将其设置为 QWidget?

c++ - 列自动调整到 QTableView 的大小

windows - 如何在 Windows 上开始 Qt 开发,但目标是 Maemo 5?

C++ 模板化 ofstream 字符以十进制打印

c++ - 将对象拷贝添加到容器的更好方法

c++ - 实现线程安全的ctime函数

c++ - C++ 中的 SQLite。数据库正忙(多线程)

java - java中 Activity 线程数中的后台线程是多少?