如果我正确理解 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()
以确保您的 MyClass
、QFuture
和 QFutureWatcher
在 QtConcurrent::run(...)
完成之前不会超出范围。
关于c++ - 如何在没有竞争条件的情况下将 QFutureWatcher 与 QtConcurrent::run() 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12527141/