QFuture Class
template <typename T> class QFutureThe QFuture class represents the result of an asynchronous computation. More...
Header: | #include <QFuture> |
CMake: | find_package(Qt6 COMPONENTS Core REQUIRED) target_link_libraries(mytarget PRIVATE Qt6::Core) |
qmake: | QT += core |
Note: All functions in this class are thread-safe with the following exceptions:
Public Types
class | const_iterator |
ConstIterator |
Public Functions
QFuture(const QFuture<T> &other) | |
QFuture() | |
QFuture<T> & | operator=(const QFuture<T> &other) |
~QFuture() | |
QFuture::const_iterator | begin() const |
void | cancel() |
QFuture::const_iterator | constBegin() const |
QFuture::const_iterator | constEnd() const |
QFuture::const_iterator | end() const |
bool | isCanceled() const |
bool | isFinished() const |
bool | isResultReadyAt(int index) const |
bool | isRunning() const |
bool | isStarted() const |
bool | isSuspended() const |
bool | isSuspending() const |
bool | isValid() const |
QFuture<T> | onCanceled(Function &&handler) |
QFuture<T> | onCanceled(QObject *context, Function &&handler) |
QFuture<T> | onFailed(Function &&handler) |
QFuture<T> | onFailed(QObject *context, Function &&handler) |
int | progressMaximum() const |
int | progressMinimum() const |
QString | progressText() const |
int | progressValue() const |
T | result() const |
T | resultAt(int index) const |
int | resultCount() const |
QList<T> | results() const |
void | resume() |
void | setSuspended(bool suspend) |
void | suspend() |
T | takeResult() |
QFuture<ResultType<Function>> | then(Function &&function) |
QFuture<ResultType<Function>> | then(QtFuture::Launch policy, Function &&function) |
QFuture<ResultType<Function>> | then(QThreadPool *pool, Function &&function) |
QFuture<ResultType<Function>> | then(QObject *context, Function &&function) |
void | toggleSuspended() |
void | waitForFinished() |
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<QByteArray, QNetworkReply::NetworkError>; enum class IOError { FailedToRead, FailedToWrite }; using IOResult = std::variant<QString, IOError>;
And we combine the two operations using then():
QFuture<IOResult> future = QtConcurrent::run([url] { ... return NetworkReply(QNetworkReply::TimeoutError); }).then([](NetworkReply reply) { if (auto error = std::get_if<QNetworkReply::NetworkError>(&reply)) return IOResult(IOError::FailedToRead); auto data = std::get_if<QByteArray>(&reply); // try to write *data and return IOError::FailedToWrite on failure ... }); auto result = future.result(); if (auto filePath = std::get_if<QString>(&result)) { // do something with *filePath else // process the error
It's possible to chain multiple continuations and handlers in any order. For example:
QFuture<int> testFuture = ...; auto resultFuture = testFuture.then([](int res) { // Block 1 }).onCanceled([] { // Block 2 }).onFailed([] { // Block 3 }).then([] { // Block 4 }).onFailed([] { // Block 5 }).onCanceled([] { // Block 6 });
Depending on the state of testFuture
(canceled, has exception or has a result), the next onCanceled(), onFailed() or then() will be called. So 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.
Note: 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<int> 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<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.
A ready QFuture object with a value or a QFuture object holding exception can be created using convenience functions QtFuture::makeReadyFuture and QtFuture::makeExceptionalFuture.
Note: To start a computation and store results in a QFuture, use QPromise or one of the APIs in the Qt Concurrent framework.
See also QPromise, QtFuture::connect(), QtFuture::makeReadyFuture(), QtFuture::makeExceptionalFuture(), QFutureWatcher, and Qt Concurrent.
Member Function Documentation
QFuture::QFuture(const QFuture<T> &other)
Constructs a copy of other.
See also operator=().
QFuture::QFuture()
Constructs an empty, canceled future.
QFuture<T> &QFuture::operator=(const QFuture<T> &other)
Assigns other to this future and returns a reference to this future.
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.
template <typename U, typename> QFuture::const_iterator QFuture::begin() const
Returns a const STL-style iterator pointing to the first result in the future.
See also constBegin() and 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.
template <typename U, typename> QFuture::const_iterator QFuture::constBegin() const
Returns a const STL-style iterator pointing to the first result in the future.
See also begin() and constEnd().
template <typename U, typename> 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 constBegin() and end().
template <typename U, typename> 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 begin() and constEnd().
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
.
template <typename U, typename> bool QFuture::isResultReadyAt(int index) const
Returns true
if the result at index is immediately available; otherwise returns false
.
Note: Calling isResultReadyAt() leads to undefined behavior if isValid() returns false
for this QFuture.
See also resultAt(), resultCount(), and 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 setSuspended(), toggleSuspended(), and 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 setSuspended(), toggleSuspended(), and 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 takeResult(), result(), results(), and resultAt().
[since 6.0]
template <typename Function, typename> QFuture<T> QFuture::onCanceled(Function &&handler)
Attaches a cancellation handler to this future, to be called when or if the future is canceled. The handler is a callable which doesn't take any arguments. It will be invoked in the same thread that canceled the promise associated with this future. If the continuation is attached after this future has already finished, it will be invoked immediately, in the thread that executes onCanceled()
.
This function was introduced in Qt 6.0.
See also then() and onFailed().
[since 6.1]
template <typename Function, typename> QFuture<T> QFuture::onCanceled(QObject *context, Function &&handler)
This is an overloaded function.
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 thread of the context object. This can be useful if the cancellation needs to be handled in a specific thread.
Note: When calling this method, it should be guaranteed that the context stays alive throughout the execution of the chain.
This function was introduced in Qt 6.1.
See also then() and onFailed().
[since 6.0]
template <typename Function, typename> 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 same type as this future. The handler will be invoked only in case of an exception, in the same thread that reported that the promise associated with this future is finished with an exception. If the handler is attached after this future has already finished, it will be invoked immediately, in the thread that executes onFailed()
. handler is a callable which takes either no argument or one argument, to filter by specific error types, similar to the catch statement.
For example:
QFuture<int> future = ...; auto resultFuture = future.then([](int res) { ... throw Error(); ... }).onFailed([](const Error &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<int> future = ...; future.then([](int res) { ... throw std::runtime_error("message"); ... }).onFailed([](const std::exception &e) { // This handler will be invoked }).onFailed([](const std::runtime_error &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<int> future = ...; auto resultFuture = future.then([](int res) { ... throw Error("message"); ... }).onFailed([](const std::exception &e) { // Won't be invoked }).onFailed([](const QException &e) { // Won't be invoked }); try { auto result = resultFuture.result(); } catch(...) { // Handle the exception }
Note: 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 then() and onCanceled().
[since 6.1]
template <typename Function, typename> QFuture<T> QFuture::onFailed(QObject *context, Function &&handler)
This is an overloaded function.
Attaches a failure handler to this future, to handle any exceptions that the future raises, or that it has already raised. Returns a QFuture of the same type as this future. The handler will be invoked only in case of an exception, in the thread of the context object. This can be useful if the failure needs to be handled in a specific thread. For example:
// somewhere in the main thread auto future = QtConcurrent::run([] { // This will run in a separate thread ... throw std::exception(); }).onFailed(this, [] { // Update UI elements });
The failure handler attached into QtConcurrent::run updates the UI elements and cannot be invoked from a non-gui thread. So this
is provided as a context to .onFailed()
, to make sure that it will be invoked in the main thread.
Note: When calling this method, it should be guaranteed that the context stays alive throughout the execution of the chain.
This function was introduced in Qt 6.1.
See also then() and onCanceled().
int QFuture::progressMaximum() const
Returns the maximum progressValue().
See also progressValue() and progressMinimum().
int QFuture::progressMinimum() const
Returns the minimum progressValue().
See also progressValue() and progressMaximum().
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 progressMinimum() and progressMaximum().
template <typename U, typename> 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.
Note: Calling result()
leads to undefined behavior if isValid() returns false
for this QFuture.
See also resultAt(), results(), and takeResult().
template <typename U, typename> 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.
Note: Calling resultAt() leads to undefined behavior if isValid() returns false
for this QFuture.
See also result(), results(), takeResult(), and 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 result(), resultAt(), results(), and takeResult().
template <typename U, typename> 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.
Note: Calling results()
leads to undefined behavior if isValid() returns false
for this QFuture.
See also result(), resultAt(), takeResult(), resultCount(), and isValid().
void QFuture::resume()
Resumes the asynchronous computation represented by the future(). This is a convenience method that simply calls setSuspended(false).
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 isSuspended(), suspend(), resume(), and 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 resume().
[since 6.0]
template <typename U, typename> 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
.
Note: 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 result(), results(), resultAt(), and isValid().
[since 6.0]
template <typename Function> 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, using the Sync policy. This method returns a new QFuture representing the result of the continuation.
Note: 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<int> future = ...; future.then([](int res1){ ... }).then([](int res2){ ... })...
Or:
QFuture<void> 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<int> future = ...; future.then([](QFuture<int> f) { try { ... auto result = f.result(); ... } catch (QException &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<int> future = ...; auto continuation = future.then([](int res1){ ... }).then([](int res2){ ... })... ... // future throws an exception try { auto result = continuation.result(); } catch (QException &e) { // handle the exception }
In this case the whole chain of continuations will be interrupted.
Note: If this future gets canceled, the continuations attached to it will also be canceled.
This function was introduced in Qt 6.0.
See also onFailed() and onCanceled().
[since 6.0]
template <typename Function> 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 be invoked in the same thread as this future, in a new thread, or will inherit the launch policy and thread pool of this future. If no launch policy is specified (see the overload taking only a callable), the Sync
policy will be used.
In the following example both continuations will be invoked in a new thread (but in the same one).
QFuture<int> future = ...; future.then(QtFuture::Launch::Async, [](int res){ ... }).then([](int res2){ ... });
In the following example both continuations will be invoked in new threads using the same thread pool.
QFuture<int> future = ...; future.then(QtFuture::Launch::Async, [](int res){ ... }) .then(QtFuture::Launch::Inherit, [](int res2){ ... });
This function was introduced in Qt 6.0.
See also onFailed() and onCanceled().
[since 6.0]
template <typename Function> 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 onFailed() and onCanceled().
[since 6.1]
template <typename Function> QFuture<ResultType<Function>> QFuture::then(QObject *context, 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 thread of the context object. This can be useful if the continuation needs to be invoked in a specific thread. For example:
// somewhere in the main thread auto future = QtConcurrent::run([] { // This will run in a separate thread ... }).then(this, [] { // Update UI elements });
The continuation attached into QtConcurrent::run updates the UI elements and cannot be invoked from a non-gui thread. So this
is provided as a context to .then()
, to make sure that it will be invoked in the main thread.
The following continuations will be also invoked from the same context, unless a different context or launch policy is specified:
auto future = QtConcurrent::run([] { ... }).then(this, [] { // Update UI elements }).then([] { // This will also run in the main thread });
This is because by default .then()
is invoked from the same thread as the previous one.
But note that if the continuation is attached after this future has already finished, it will be invoked immediately, in the thread that executes then()
:
QObject *context = ...; auto future = cachedResultsReady ? QtFuture::makeReadyFuture(results) : QtConcurrent::run([] { /* compute results */}); auto continuation = future.then(context, [] (Results results) { // Runs in the context's thread }).then([] { // May or may not run in the context's thread });
In the above example if cachedResultsReady
is true
, and a ready future is returned, it is possible that the first .then()
finishes before the second one is attached. In this case it will be resolved in the current thread. Therefore, when in doubt, pass the context explicitly.
Note: When calling this method, it should be guaranteed that the context stays alive throughout the execution of the chain.
This function was introduced in Qt 6.1.
See also onFailed() and 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 setSuspended(), suspend(), and resume().
void QFuture::waitForFinished()
Waits for the asynchronous computation to finish (including cancel()ed computations), i.e. until isFinished() returns true
.