c++ - 如何在没有竞争条件的情况下将 QFutureWatcher 与 QtConcurrent::run() 一起使用

标签 c++ qt concurrency future

如果我正确理解 QFutureWatcher 文档中的以下代码,那么在最后一行之间存在竞争条件:

// Instantiate the objects and connect to the finished signal.
MyClass myObject;
QFutureWatcher<int> watcher;
connect(&watcher, SIGNAL(finished()), &myObject, SLOT(handleFinished()));

// Start the computation.
QFuture<int> future = QtConcurrent::run(...);
watcher.setFuture(future);

如果 QtConcurrent::run(...) 中的函数 ... 在调用下一行之前完成,则 watcher.finished () 信号永远不会被触发。我的假设正确吗?我该如何解决这个错误?

最佳答案

来自 http://doc.qt.io/qt-4.8/qfuturewatcher.html#setFuture

One of the signals might be emitted for the current state of the future. For example, if the future is already stopped, the finished signal will be emitted.

换句话说,如果 QtConcurrent::run(...) 在调用 setFuture 之前完成,setFuture 仍会发出信号QFuture 的当前状态。因此,您无需执行任何操作即可避免竞争条件。

但是,根据您的其余代码,您可能需要调用 QFuture::waitForFinished() 以确保您的 MyClassQFuture QFutureWatcher QtConcurrent::run(...) 完成之前不会超出范围。

关于c++ - 如何在没有竞争条件的情况下将 QFutureWatcher 与 QtConcurrent::run() 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12527141/

相关文章:

c++ - QTextBrowser:如何突出显示单击的行

user-interface - 在 Qt 中重新排序小部件

sql-server - 事务级别、nolock/readpast 和并发性

java - 双重检查锁定保证对象的状态 ? (实践中的并发)

c++ - 在 Crypto++ 中使用 std::string 作为 AES 加密的 key

c++ - Google Test 宏似乎不适用于 Lambda 函数

c++ - 是否保证 size_t、vector::size_type 等 typedef 不会绑定(bind)到 char 类型?

c++ - 根据条件 C++ 从 vector 中复制元素

c++ - 使用现有 C 程序编写 Qt 程序时未找到符号

node.js - Go 会阻塞像 Node 这样的处理器密集型操作吗?