QFuture Class▲
-
Header: QFuture
-
CMake:
find_package(Qt6 REQUIRED COMPONENTS Core)
target_link_libraries(mytarget PRIVATE Qt6::Core)
-
qmake: QT += core
-
Group: QFuture is part of thread
Detailed Description▲
QFuture allows threads to be synchronized against one or more results which will be ready at a later point in time. The result can be of any type that has default, copy and possibly move constructors. If a result is not available at the time of calling the result(), resultAt(), results() and takeResult() functions, QFuture will wait until the result becomes available. You can use the isResultReadyAt() function to determine if a result is ready or not. For QFuture objects that report more than one result, the resultCount() function returns the number of continuous results. This means that it is always safe to iterate through the results from 0 to resultCount(). takeResult() invalidates a future, and any subsequent attempt to access result or results from the future leads to undefined behavior. isValid() tells you if results can be accessed.
QFuture provides a Java-style iterator (QFutureIterator) and an STL-style iterator (QFuture::const_iterator). Using these iterators is another way to access results in the future.
If the result of one asynchronous computation needs to be passed to another, QFuture provides a convenient way of chaining multiple sequential computations using then(). onCanceled() can be used for adding a handler to be called if the QFuture is canceled. Additionally, onFailed() can be used to handle any failures that occurred in the chain. Note that QFuture relies on exceptions for the error handling. If using exceptions is not an option, you can still indicate the error state of QFuture, by making the error type part of the QFuture type. For example, you can use std::variant, std::any or similar for keeping the result or failure or make your custom type.
The example below demonstrates how the error handling can be done without using exceptions. Let's say we want to send a network request to obtain a large file from a network location. Then we want to write it to the file system and return its location in case of a success. Both of these operations may fail with different errors. So, we use std::variant to keep the result or error:
using
NetworkReply =
std::
variant&
lt;QByteArray, QNetworkReply::
NetworkError&
gt;;
enum
class
IOError {
FailedToRead, FailedToWrite }
;
using
IOResult =
std::
variant&
lt;QString, IOError&
gt;;
And we combine the two operations using then():
QFuture&
lt;IOResult&
gt; future =
QtConcurrent::
run([url] {
...
return
NetworkReply(QNetworkReply::
TimeoutError);
}
).then([](NetworkReply reply) {
if
(auto
error =
std::
get_if&
lt;QNetworkReply::
NetworkError&
gt;(&
amp;reply))
return
IOResult(IOError::
FailedToRead);
auto
data =
std::
get_if&
lt;QByteArray&
gt;(&
amp;reply);
// try to write *data and return IOError::FailedToWrite on failure
...
}
);
auto
result =
future.result();
if
(auto
filePath =
std::
get_if&
lt;QString&
gt;(&
amp;result)) {
// do something with *filePath
else
// process the error
It's possible to chain multiple continuations and handlers in any order. The first handler that can handle the state of its parent is invoked first. If there's no proper handler, the state is propagated to the next continuation or handler. For example:
QFuture&
lt;int
&
gt; testFuture =
...;
auto
resultFuture =
testFuture.then([](int
res) {
// Block 1
}
).onCanceled([] {
// Block 2
}
).onFailed([] {
// Block 3
}
).then([] {
// Block 4
}
).onFailed([] {
// Block 5
}
).onCanceled([] {
// Block 6
}
);
If testFuture is successfully fulfilled Block 1 will be called. If it succeeds as well, the next then() (Block 4) is called. If testFuture gets canceled or fails with an exception, either Block 2 or Block 3 will be called respectively. The next then() will be called afterwards, and the story repeats.
If Block 2 is invoked and throws an exception, the following onFailed() (Block 3) will handle it. If the order of onFailed() and onCanceled() were reversed, the exception state would propagate to the next continuations and eventually would be caught in Block 5.
In the next example the first onCanceled() (Block 2) is removed:
QFuture&
lt;int
&
gt; testFuture =
...;
auto
resultFuture =
testFuture.then([](int
res) {
// Block 1
}
).onFailed([] {
// Block 3
}
).then([] {
// Block 4
}
).onFailed([] {
// Block 5
}
).onCanceled([] {
// Block 6
}
);
If testFuture gets canceled, its state is propagated to the next then(), which will be also canceled. So in this case Block 6 will be called.
QFuture also offers ways to interact with a runnning computation. For instance, the computation can be canceled with the cancel() function. To suspend or resume the computation, use the setSuspended() function or one of the suspend(), resume(), or toggleSuspended() convenience functions. Be aware that not all running asynchronous computations can be canceled or suspended. For example, the future returned by QtConcurrent::run() cannot be canceled; but the future returned by QtConcurrent::mappedReduced() can.
Progress information is provided by the progressValue(), progressMinimum(), progressMaximum(), and progressText() functions. The waitForFinished() function causes the calling thread to block and wait for the computation to finish, ensuring that all results are available.
The state of the computation represented by a QFuture can be queried using the isCanceled(), isStarted(), isFinished(), isRunning(), isSuspending() or isSuspended() functions.
QFuture is a lightweight reference counted class that can be passed by value.
QFuture<void> is specialized to not contain any of the result fetching functions. Any QFuture<T> can be assigned or copied into a QFuture<void> as well. This is useful if only status or progress information is needed - not the actual result data.
To interact with running tasks using signals and slots, use QFutureWatcher.
You can also use QtFuture::connect to connect signals to a QFuture object which will be resolved when a signal is emitted. This allows working with signals like with QFuture objects. For example, if you combine it with then(), you can attach multiple continuations to a signal, which are invoked in the same thread or a new thread.
To start a computation and store results in a QFuture, use QPromise or one of the APIs in the Qt Concurrent framework.
See Also▲
See also QPromise, QtFuture::connect(), QFutureWatcher, Qt Concurrent
Member Type Documentation▲
Member Function Documentation▲
QFuture::QFuture()▲
Constructs an empty, canceled future.
QFuture::QFuture(const QFuture<T> &other)▲
QFuture::~QFuture()▲
Destroys the future.
Note that this neither waits nor cancels the asynchronous computation. Use waitForFinished() or QFutureSynchronizer when you need to ensure that the computation is completed before the future is destroyed.
QFuture::const_iterator QFuture::begin() const▲
Returns a const STL-style iterator pointing to the first result in the future.
See Also▲
See also constBegin(), end()
void QFuture::cancel()▲
Cancels the asynchronous computation represented by this future. Note that the cancelation is asynchronous. Use waitForFinished() after calling cancel() when you need synchronous cancelation.
Results currently available may still be accessed on a canceled future, but new results will not become available after calling this function. Any QFutureWatcher object that is watching this future will not deliver progress and result ready signals on a canceled future.
Be aware that not all running asynchronous computations can be canceled. For example, the future returned by QtConcurrent::run() cannot be canceled; but the future returned by QtConcurrent::mappedReduced() can.
QFuture::const_iterator QFuture::constBegin() const▲
Returns a const STL-style iterator pointing to the first result in the future.
See Also▲
QFuture::const_iterator QFuture::constEnd() const▲
Returns a const STL-style iterator pointing to the imaginary result after the last result in the future.
See Also▲
See also constBegin(), end()
QFuture::const_iterator QFuture::end() const▲
Returns a const STL-style iterator pointing to the imaginary result after the last result in the future.
See Also▲
bool QFuture::isCanceled() const▲
Returns true if the asynchronous computation has been canceled with the cancel() function; otherwise returns false.
Be aware that the computation may still be running even though this function returns true. See cancel() for more details.
bool QFuture::isFinished() const▲
Returns true if the asynchronous computation represented by this future has finished; otherwise returns false.
bool QFuture::isResultReadyAt(int index) const▲
Returns true if the result at index is immediately available; otherwise returns false.
See Also▲
See also resultAt(), resultCount(), takeResult()
bool QFuture::isRunning() const▲
Returns true if the asynchronous computation represented by this future is currently running; otherwise returns false.
bool QFuture::isStarted() const▲
Returns true if the asynchronous computation represented by this future has been started; otherwise returns false.
[since 6.0] bool QFuture::isSuspended() const▲
Returns true if a suspension of the asynchronous computation has been requested, and it is in effect, meaning that no more results or progress changes are expected.
This function was introduced in Qt 6.0.
See Also▲
See also setSuspended(), toggleSuspended(), isSuspending()
[since 6.0] bool QFuture::isSuspending() const▲
Returns true if the asynchronous computation has been suspended with the suspend() function, but the work is not yet suspended, and computation is still running. Returns false otherwise.
To check if suspension is actually in effect, use isSuspended() instead.
This function was introduced in Qt 6.0.
See Also▲
See also setSuspended(), toggleSuspended(), isSuspended()
[since 6.0] bool QFuture::isValid() const▲
Returns true if a result or results can be accessed or taken from this QFuture object. Returns false after the result was taken from the future.
This function was introduced in Qt 6.0.
See Also▲
See also takeResult(), result(), results(), resultAt()
[since 6.0] QFuture<T> QFuture::onCanceled(Function &&handler)▲
Attaches a cancellation handler to this future, to be called when the future is canceled. The handler is a callable which doesn't take any arguments. It will be invoked in the same thread in which this future has been running. If the continuation is attached after the parent has already finished, it will be invoked in the thread where the parent lives.
This function was introduced in Qt 6.0.
See Also▲
[since 6.0] QFuture<T> QFuture::onFailed(Function &&handler)▲
Attaches a failure handler to this future, to handle any exceptions that may have been generated. Returns a QFuture of the parent type. The handler will be invoked only in case of an exception, in the same thread as the parent future has been running. If the continuation is attached after the parent has already finished, it will be invoked in the thread where the parent lives. handler is a callable which takes either no argument or one argument, to filter by specific error types similar to catch statement.
For example:
QFuture&
lt;int
&
gt; future =
...;
auto
resultFuture =
future.then([](int
res) {
...
throw
Error();
...
}
).onFailed([](const
Error &
amp;e) {
// Handle exceptions of type Error
...
return
-
1
;
}
).onFailed([] {
// Handle all other types of errors
...
return
-
1
;
}
);
auto
result =
resultFuture.result(); // result is -1
If there are multiple handlers attached, the first handler that matches with the thrown exception type will be invoked. For example:
QFuture&
lt;int
&
gt; future =
...;
future.then([](int
res) {
...
throw
std::
runtime_error("message"
);
...
}
).onFailed([](const
std::
exception &
amp;e) {
// This handler will be invoked
}
).onFailed([](const
std::
runtime_error &
amp;e) {
// This handler won't be invoked, because of the handler above.
}
);
If none of the handlers matches with the thrown exception type, the exception will be propagated to the resulted future:
QFuture&
lt;int
&
gt; future =
...;
auto
resultFuture =
future.then([](int
res) {
...
throw
Error("message"
);
...
}
).onFailed([](const
std::
exception &
amp;e) {
// Won't be invoked
}
).onFailed([](const
QException &
amp;e) {
// Won't be invoked
}
);
try
{
auto
result =
resultFuture.result();
}
catch
(...) {
// Handle the exception
}
You can always attach a handler taking no argument, to handle all exception types and avoid writing the try-catch block.
This function was introduced in Qt 6.0.
See Also▲
See also then(), onCanceled()
int QFuture::progressMaximum() const▲
int QFuture::progressMinimum() const▲
QString QFuture::progressText() const▲
Returns the (optional) textual representation of the progress as reported by the asynchronous computation.
Be aware that not all computations provide a textual representation of the progress, and as such, this function may return an empty string.
int QFuture::progressValue() const▲
Returns the current progress value, which is between the progressMinimum() and progressMaximum().
See Also▲
See also progressMinimum(), progressMaximum()
T QFuture::result() const▲
Returns the first result in the future. If the result is not immediately available, this function will block and wait for the result to become available. This is a convenience method for calling resultAt(0). Note that result() returns a copy of the internally stored result. If T is a move-only type, or you don't want to copy the result, use takeResult() instead.
See Also▲
See also resultAt(), results(), takeResult()
T QFuture::resultAt(int index) const▲
Returns the result at index in the future. If the result is not immediately available, this function will block and wait for the result to become available.
See Also▲
See also result(), results(), takeResult(), resultCount()
int QFuture::resultCount() const▲
Returns the number of continuous results available in this future. The real number of results stored might be different from this value, due to gaps in the result set. It is always safe to iterate through the results from 0 to resultCount().
See Also▲
See also result(), resultAt(), results(), takeResult()
QList<T> QFuture::results() const▲
Returns all results from the future. If the results are not immediately available, this function will block and wait for them to become available. Note that results() returns a copy of the internally stored results. Getting all results of a move-only type T is not supported at the moment. However you can still iterate through the list of move-only results by using STL-style iterators or read-only Java-style iterators.
See Also▲
See also result(), resultAt(), takeResult(), resultCount(), isValid()
void QFuture::resume()▲
Resumes the asynchronous computation represented by the future(). This is a convenience method that simply calls setSuspended(false).
See Also▲
See also suspend()
[since 6.0] void QFuture::setSuspended(bool suspend)▲
If suspend is true, this function suspends the asynchronous computation represented by the future(). If the computation is already suspended, this function does nothing. QFutureWatcher will not immediately stop delivering progress and result ready signals when the future is suspended. At the moment of suspending there may still be computations that are in progress and cannot be stopped. Signals for such computations will still be delivered.
If suspend is false, this function resumes the asynchronous computation. If the computation was not previously suspended, this function does nothing.
Be aware that not all computations can be suspended. For example, the QFuture returned by QtConcurrent::run() cannot be suspended; but the QFuture returned by QtConcurrent::mappedReduced() can.
This function was introduced in Qt 6.0.
See Also▲
See also isSuspended(), suspend(), resume(), toggleSuspended()
[since 6.0] void QFuture::suspend()▲
Suspends the asynchronous computation represented by this future. This is a convenience method that simply calls setSuspended(true).
This function was introduced in Qt 6.0.
See Also▲
See also resume()
[since 6.0] T QFuture::takeResult()▲
Call this function only if isValid() returns true, otherwise the behavior is undefined. This function takes (moves) the first result from the QFuture object, when only one result is expected. If there are any other results, they are discarded after taking the first one. If the result is not immediately available, this function will block and wait for the result to become available. The QFuture will try to use move semantics if possible, and will fall back to copy construction if the type is not movable. After the result was taken, isValid() will evaluate as false.
QFuture in general allows sharing the results between different QFuture objects (and potentially between different threads). takeResult() was introduced to make QFuture also work with move-only types (like std::unique_ptr), so it assumes that only one thread can move the results out of the future, and do it only once. Also note that taking the list of all results is not supported at the moment. However you can still iterate through the list of move-only results by using STL-style iterators or read-only Java-style iterators.
This function was introduced in Qt 6.0.
See Also▲
[since 6.0] QFuture<ResultType<Function>> QFuture::then(Function &&function)▲
This is an overloaded function.
Attaches a continuation to this future, allowing to chain multiple asynchronous computations if desired. When the asynchronous computation represented by this future finishes, function will be invoked in the same thread in which this future has been running. If the continuation is attached after the parent has already finished, it will be invoked in the thread where the parent lives. This method returns a new QFuture representing the result of the continuation.
Use other overloads of this method if you need to launch the continuation in a separate thread.
If this future has a result (is not a QFuture<void>), function takes the result of this future as its argument.
You can chain multiple operations like this:
QFuture&
lt;int
&
gt; future =
...;
future.then([](int
res1){
... }
).then([](int
res2){
... }
)...
Or:
QFuture&
lt;void
&
gt; future =
...;
future.then([](){
... }
).then([](){
... }
)...
The continuation can also take a QFuture argument (instead of its value), representing the previous future. This can be useful if, for example, QFuture has multiple results, and the user wants to access them inside the continuation. Or the user needs to handle the exception of the previous future inside the continuation, to not interrupt the chain of multiple continuations. For example:
QFuture&
lt;int
&
gt; future =
...;
future.then([](QFuture&
lt;int
&
gt; f) {
try
{
...
auto
result =
f.result();
...
}
catch
(QException &
amp;e) {
// handle the exception
}
}
).then(...);
If the previous future throws an exception and it is not handled inside the continuation, the exception will be propagated to the continuation future, to allow the caller to handle it:
QFuture&
lt;int
&
gt; parentFuture =
...;
auto
continuation =
parentFuture.then([](int
res1){
... }
).then([](int
res2){
... }
)...
...
// parentFuture throws an exception
try
{
auto
result =
continuation.result();
}
catch
(QException &
amp;e) {
// handle the exception
}
In this case the whole chain of continuations will be interrupted.
If the parent future gets canceled, its continuations will also be canceled.
This function was introduced in Qt 6.0.
See Also▲
See also onFailed(), onCanceled()
[since 6.0] QFuture<ResultType<Function>> QFuture::then(QtFuture::Launch policy, Function &&function)▲
This is an overloaded function.
Attaches a continuation to this future, allowing to chain multiple asynchronous computations. When the asynchronous computation represented by this future finishes, function will be invoked according to the given launch policy. A new QFuture representing the result of the continuation is returned.
Depending on the policy, continuation will run in the same thread as the parent, run in a new thread, or inherit the launch policy and thread pool of the parent.
In the following example both continuations will run in a new thread (but in the same one).
QFuture&
lt;int
&
gt; future =
...;
future.then(QtFuture::Launch::
Async, [](int
res){
... }
).then([](int
res2){
... }
);
In the following example both continuations will run in new threads using the same thread pool.
QFuture&
lt;int
&
gt; future =
...;
future.then(QtFuture::Launch::
Async, [](int
res){
... }
)
.then(QtFuture::Launch::
Inherit, [](int
res2){
... }
);
This function was introduced in Qt 6.0.
See Also▲
See also onFailed(), onCanceled()
[since 6.0] QFuture<ResultType<Function>> QFuture::then(QThreadPool *pool, Function &&function)▲
This is an overloaded function.
Attaches a continuation to this future, allowing to chain multiple asynchronous computations if desired. When the asynchronous computation represented by this future finishes, function will be invoked in a separate thread taken from the QThreadPool pool.
This function was introduced in Qt 6.0.
See Also▲
See also onFailed(), onCanceled()
[since 6.0] void QFuture::toggleSuspended()▲
Toggles the suspended state of the asynchronous computation. In other words, if the computation is currently suspending or suspended, calling this function resumes it; if the computation is running, it is suspended. This is a convenience method for calling setSuspended(!(isSuspending() || isSuspended())).
This function was introduced in Qt 6.0.
See Also▲
See also setSuspended(), suspend(), resume()
void QFuture::waitForFinished()▲
Waits for the asynchronous computation to finish (including cancel()ed computations), i.e. until isFinished() returns true.
QFuture<T> &QFuture::operator=(const QFuture<T> &other)▲
Assigns other to this future and returns a reference to this future.
Obsolete Members for QFuture▲
The following members of class QFuture are deprecated. We strongly advise against using them in new code.
Obsolete Member Function Documentation▲
bool QFuture::isPaused() const▲
This function is deprecated. We strongly advise against using it in new code.
Use isSuspending() or isSuspended() instead.
Returns true if the asynchronous computation has been paused with the pause() function; otherwise returns false.
Be aware that the computation may still be running even though this function returns true. See setPaused() for more details. To check if pause actually took effect, use isSuspended() instead.
See Also▲
See also setPaused(), togglePaused(), isSuspended()
void QFuture::pause()▲
This function is deprecated. We strongly advise against using it in new code.
Use suspend() instead.
Pauses the asynchronous computation represented by this future. This is a convenience method that simply calls setPaused(true).
See Also▲
See also resume()
void QFuture::setPaused(bool paused)▲
This function is deprecated. We strongly advise against using it in new code.
Use setSuspended() instead.
If paused is true, this function pauses the asynchronous computation represented by the future. If the computation is already paused, this function does nothing. Any QFutureWatcher object that is watching this future will stop delivering progress and result ready signals while the future is paused. Signal delivery will continue once the future is resumed.
If paused is false, this function resumes the asynchronous computation. If the computation was not previously paused, this function does nothing.
Be aware that not all computations can be paused. For example, the future returned by QtConcurrent::run() cannot be paused; but the future returned by QtConcurrent::mappedReduced() can.
See Also▲
See also isPaused(), pause(), resume(), togglePaused()
void QFuture::togglePaused()▲
This function is deprecated. We strongly advise against using it in new code.
Use toggleSuspended() instead.
Toggles the paused state of the asynchronous computation. In other words, if the computation is currently paused, calling this function resumes it; if the computation is running, it is paused. This is a convenience method for calling setPaused(!isPaused()).