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▲
https:// 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 https://(), https://(), https://() and https://() functions, https:// will wait until the result becomes available. You can use the https://() function to determine if a result is ready or not. For https:// objects that report more than one result, the https://() function returns the number of continuous results. This means that it is always safe to iterate through the results from 0 to https://(). https://() invalidates a future, and any subsequent attempt to access result or results from the future leads to undefined behavior. https://() tells you if results can be accessed.
https:// provides a https:// (https://) and an https:// (https://). 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, https:// provides a convenient way of chaining multiple sequential computations using https://(). https://() can be used for adding a handler to be called if the https:// is canceled. Additionally, https://() can be used to handle any failures that occurred in the chain. Note that https:// relies on exceptions for the error handling. If using exceptions is not an option, you can still indicate the error state of https://, by making the error type part of the https:// 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 https://():
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 errorIt'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 https://(), https://() or https://() will be called. So if testFuture is successfully fulfilled, Block 1 will be called. If it succeeds as well, the next https://() (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 https://() will be called afterwards, and the story repeats.
If Block 2 is invoked and throws an exception, the following https://() (Block 3) will handle it. If the order of https://() and https://() 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 https://() (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 https://(), which will be also canceled. So in this case Block 6 will be called.
https:// also offers ways to interact with a running computation. For instance, the computation can be canceled with the https://() function. To suspend or resume the computation, use the https://() function or one of the https://(), https://(), or https://() 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 https://(), https://(), https://(), and https://() functions. The https://() 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 https:// can be queried using the https://(), https://(), https://(), https://(), https://() or https://() functions.
https://<void> is specialized to not contain any of the result fetching functions. Any https://<T> can be assigned or copied into a https://<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 https://.
You can also use https://() to connect signals to a https:// object which will be resolved when a signal is emitted. This allows working with signals like with https:// objects. For example, if you combine it with https://(), you can attach multiple continuations to a signal, which are invoked in the same thread or a new thread.
The https://() and https://() functions can be used to combine several futures and track when the last or first of them completes.
A ready https:// object with a value or a https:// object holding exception can be created using convenience functions https://() and https://().
To start a computation and store results in a https://, use https:// or one of the APIs in the https:// framework.
See Also▲
See also https://, https://(), https://(), https://(), https://, https://
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 https://() or https:// when you need to ensure that the computation is completed before the future is destroyed.
QFuture::const_iterator QFuture::begin() const▲
Returns a const https:// pointing to the first result in the future.
See Also▲
See also https://(), https://()
void QFuture::cancel()▲
Cancels the asynchronous computation represented by this future. Note that the cancellation is asynchronous. Use https://() after calling cancel() when you need synchronous cancellation.
Results currently available may still be accessed on a canceled future, but new results will not become available after calling this function. Any https:// 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 https:// pointing to the first result in the future.
See Also▲
See also https://(), https://()
QFuture::const_iterator QFuture::constEnd() const▲
Returns a const https:// pointing to the imaginary result after the last result in the future.
See Also▲
See also https://(), https://()
QFuture::const_iterator QFuture::end() const▲
Returns a const https:// pointing to the imaginary result after the last result in the future.
See Also▲
See also https://(), https://()
bool QFuture::isCanceled() const▲
Returns true if the asynchronous computation has been canceled with the https://() function; otherwise returns false.
Be aware that the computation may still be running even though this function returns true. See https://() 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.
Calling isResultReadyAt() leads to undefined behavior if https://() returns false for this https://.
See Also▲
See also https://(), https://(), https://()
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 https://(), https://(), https://()
[since 6.0] bool QFuture::isSuspending() const▲
Returns true if the asynchronous computation has been suspended with the https://() 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 https://() instead.
This function was introduced in Qt 6.0.
See Also▲
See also https://(), https://(), https://()
[since 6.0] bool QFuture::isValid() const▲
Returns true if a result or results can be accessed or taken from this https:// object. Returns false after the result was taken from the future.
This function was introduced in Qt 6.0.
See Also▲
See also https://(), https://(), https://(), https://()
[since 6.0] QFuture<T> QFuture::onCanceled(Function &&handler)▲
Attaches a cancellation handler to this future. The returned future behaves exactly as this future (has the same state and result) unless this future is cancelled. The handler is a callable which takes no arguments and returns a value of the type packaged by this future. After cancellation, the returned future packages the value returned by handler.
If attached before the cancellation, handler will be invoked in the same thread that reports the future as finished after the cancellation. If the handler is attached after this future has already been canceled, it will be invoked immediately in the thread that executes onCanceled(). Therefore, the handler cannot always make assumptions about which thread it will be run on. Use the overload that takes a context object if you want to control which thread the handler is invoked on.
The example below demonstrates how to attach a cancellation handler:
QFuture<int> testFuture = ...;
auto resultFuture = testFuture.then([](int res) {
// Block 1
...
return 1;
}).then([](int res) {
// Block 2
...
return 2;
}).onCanceled([] {
// Block 3
...
return -1;
});If testFuture is canceled, Block 3 will be called and the resultFuture will have -1 as its result. Unlike testFuture, it won't be in a Canceled state. This means that you can get its result, attach countinuations to it, and so on.
Also note that you can cancel the chain of continuations while they are executing via the future that started the chain. Let's say testFuture.cancel() was called while Block 1 is already executing. The next continuation will detect that cancellation was requested, so Block 2 will be skipped, and the cancellation handler (Block 3) will be called.
This method returns a new QFuture representing the result of the continuation chain. Canceling the resulting QFuture itself won't invoke the cancellation handler in the chain that lead to it. This means that if you call resultFuture.cancel(), Block 3 won't be called: because resultFuture is the future that results from attaching the cancellation handler to testFuture, no cancellation handlers have been attached to resultFuture itself. Only cancellation of testFuture or the futures returned by continuations attached before the onCancelled() call can trigger Block 3.
This function was introduced in Qt 6.0.
See Also▲
See also https://(), https://()
[since 6.1] 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.
When calling this method, it should be guaranteed that the context stays alive throughout the execution of the chain.
See the documentation of the other overload for more details about handler.
This function was introduced in Qt 6.1.
See Also▲
See also https://(), https://()
[since 6.0] QFuture<T> QFuture::onFailed(Function &&handler)▲
Attaches a failure handler to this future, to handle any exceptions. The returned future behaves exactly as this future (has the same state and result) unless this future fails with an exception.
The handler is a callable which takes either no argument or one argument, to filter by specific error types, similar to the https:// statement. It returns a value of the type packaged by this future. After the failure, the returned future packages the value returned by handler.
The handler will only be invoked if an exception is raised. If the exception is raised after this handler is attached, the handler is executed in the thread that reports the future as finished as a result of the exception. If the handler is attached after this future has already failed, it will be invoked immediately, in the thread that executes onFailed(). Therefore, the handler cannot always make assumptions about which thread it will be run on. Use the overload that takes a context object if you want to control which thread the handler is invoked on.
The example below demonstrates how to attach a failure handler:
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 -1If 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
}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 https://(), https://()
[since 6.1] 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 https:// 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 https:// 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.
When calling this method, it should be guaranteed that the context stays alive throughout the execution of the chain.
See the documentation of the other overload for more details about handler.
This function was introduced in Qt 6.1.
See Also▲
See also https://(), https://()
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 https://() and https://().
See Also▲
See also https://(), https://()
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 https://(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 https://() instead.
Calling result() leads to undefined behavior if https://() returns false for this https://.
See Also▲
See also https://(), https://(), https://()
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.
Calling resultAt() leads to undefined behavior if https://() returns false for this https://.
See Also▲
See also https://(), https://(), https://(), https://()
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 https://(), https://(), https://(), https://()
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 https:// or read-only https://.
Calling results() leads to undefined behavior if https://() returns false for this https://.
See Also▲
See also https://(), https://(), https://(), https://(), https://()
void QFuture::resume()▲
Resumes the asynchronous computation represented by the future(). This is a convenience method that simply calls https://(false).
See Also▲
See also https://()
[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. https:// 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 https:// returned by QtConcurrent::run() cannot be suspended; but the https:// returned by QtConcurrent::mappedReduced() can.
This function was introduced in Qt 6.0.
See Also▲
See also https://(), https://(), https://(), https://()
[since 6.0] void QFuture::suspend()▲
Suspends the asynchronous computation represented by this future. This is a convenience method that simply calls https://(true).
This function was introduced in Qt 6.0.
See Also▲
See also https://()
[since 6.0] T QFuture::takeResult()▲
Call this function only if https://() returns true, otherwise the behavior is undefined. This function takes (moves) the first result from the https:// 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 https:// 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, https://() will evaluate as false.
https:// in general allows sharing the results between different https:// objects (and potentially between different threads). takeResult() was introduced to make https:// 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 https:// or read-only https://.
This function was introduced in Qt 6.0.
See Also▲
See also https://(), https://(), https://(), https://()
[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, using the https:// policy. function is a callable that takes an argument of the type packaged by this future if this has a result (is not a https://<void>). Otherwise it takes no arguments. This method returns a new https:// that packages a value of the type returned by function. The returned future will be in an uninitialized state until the attached continuation is invoked, or until this future fails or is canceled.
Use other overloads of this method if you need to launch the continuation in a separate thread.
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 https:// argument (instead of its value), representing the previous future. This can be useful if, for example, https:// 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.
If this future gets canceled, the continuations attached to it will also be canceled.
This function was introduced in Qt 6.0.
See Also▲
See also https://(), https://()
[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 https:// 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){ ... });See the documentation of the other overload for more details about function.
This function was introduced in Qt 6.0.
See Also▲
See also https://(), https://()
[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 https:// pool.
This function was introduced in Qt 6.0.
See Also▲
See also https://(), https://()
[since 6.1] 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 https:// 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.
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▲
See also https://(), https://()
[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 https://(!(https://() || https://())).
This function was introduced in Qt 6.0.
See Also▲
See also https://(), https://(), https://()
void QFuture::waitForFinished()▲
Waits for the asynchronous computation to finish (including https://()ed computations), i.e. until https://() 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 https:// are deprecated. We strongly advise against using them in new code.
Obsolete Member Function Documentation▲
bool QFuture::isPaused() const▲
This function is deprecated since 6.0. We strongly advise against using it in new code.
Use https://() or https://() instead.
Returns true if the asynchronous computation has been paused with the https://() function; otherwise returns false.
Be aware that the computation may still be running even though this function returns true. See https://() for more details. To check if pause actually took effect, use https://() instead.
See Also▲
See also https://(), https://()
void QFuture::pause()▲
This function is deprecated since 6.0. We strongly advise against using it in new code.
Use https://() instead.
Pauses the asynchronous computation represented by this future. This is a convenience method that simply calls https://(true).
See Also▲
See also https://()
void QFuture::setPaused(bool paused)▲
This function is deprecated since 6.0. We strongly advise against using it in new code.
Use https://() 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 https:// 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 https://(), https://(), https://(), https://()
void QFuture::togglePaused()▲
This function is deprecated since 6.0. We strongly advise against using it in new code.
Use https://() 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 https://(!https://()).
See Also▲
See also https://(), https://(), https://()


