如果我正确理解了QFutureWatcher文档中的以下代码,那么在最后的to行之间存在竞争条件:
// 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()信号将永远不会被触发。我的假设正确吗?我该如何解决这个bug?
发布于 2012-09-21 16:50:29
来自http://doc.qt.io/qt-4.8/qfuturewatcher.html#setFuture
可能会针对未来的当前状态发出其中一个信号。例如,如果future已经停止,则将发出finished信号。
换句话说,如果QtConcurrent::run(...)在setFuture被调用之前完成,setFuture仍然会在QFuture的当前状态上发出一个信号。因此,您不需要做任何事情来避免竞争条件。
但是,根据您代码的其余部分,您可能需要调用QFuture::waitForFinished(),以确保您的MyClass、QFuture和QFutureWatcher在QtConcurrent::run(...)完成之前不会超出范围。
发布于 2018-07-10 01:33:48
我在一个单元测试中运行了这段代码,QSignalSpy没有收到来自QFutureWatcher的信号。我通过在检查前显式地调用QCoreApplication::processEvents()解决了这个问题:
QFutureWatcher<int> watcher;
QSignalSpy spy(&watcher, &QFutureWatcher<int>::finished);
QFuture<int> future = QtConcurrent::run([](){
qDebug() << "compute";
return 42;
});
watcher.setFuture(future);
QCOMPARE(watcher.result(), 42);
QCOMPARE(spy.count(), 0);
QCoreApplication::processEvents();
QCOMPARE(spy.count(), 1);信号可能是从线程发出的,在这种情况下,信号是排队的,而不是直接执行。
https://stackoverflow.com/questions/12527141
复制相似问题