如何使用QFutureWatcher与QtConcurrent :: run()没有竞争条件 [英] How can I use a QFutureWatcher with QtConcurrent::run() without a race condition

查看:2939
本文介绍了如何使用QFutureWatcher与QtConcurrent :: run()没有竞争条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I understand the following code from the QFutureWatcher documentation correctly, then there is a race condition between the last to lines:

// 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()信号将永远不会被触发。我的假设是正确的吗?如何解决此错误?

If the function ... in the QtConcurrent::run(...) finishes before the next line is called, then the watcher.finished() signal will never be triggered. Is my assumption correct? How do I work around this bug?

推荐答案

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 当前状态的信号。所以,你不需要做任何事情,以避免竞争条件。

In other words, if QtConcurrent::run(...) completes before setFuture is called, setFuture will still emit a signal on the current state of the QFuture. So, you don't need to do anything in order to avoid a race condition.

但是,根据你的代码的其余部分,你可能需要调用 QFuture :: waitForFinished(),以确保您的 MyClass QFuture QfutureWatcher 不要超出范围 QtConcurrent :: run(...)完成。

However, depending on the rest of your code, you may need to call QFuture::waitForFinished() in order to ensure that your MyClass, QFuture and QFutureWatcher do not go out of scope before QtConcurrent::run(...) completes.

这篇关于如何使用QFutureWatcher与QtConcurrent :: run()没有竞争条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆