QFuture Class

template <typename T> class QFuture

The QFuture class represents the result of an asynchronous computation. More...

Header: #include <QFuture>
qmake: QT += core
Since: Qt 4.4

This class was introduced in Qt 4.4.

Note: All functions in this class are thread-safe with the following exceptions:

Public Types

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 isPaused() const
bool isResultReadyAt(int index) const
bool isRunning() const
bool isStarted() const
void pause()
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 setPaused(bool paused)
QFuture<ResultType<Function> > then(Function &&function)
QFuture<ResultType<Function> > then(QtFuture::Launch policy, Function &&function)
QFuture<ResultType<Function> > then(QThreadPool *pool, Function &&function)
void togglePaused()
void waitForFinished()
T operator T() const
bool operator!=(const QFuture<T> &other) const
bool operator==(const QFuture<T> &other) const

Detailed Description

To start a computation, use one of the APIs in the Qt Concurrent framework.

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 a default constructor and a copy constructor. If a result is not available at the time of calling the result(), resultAt(), or results() 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().

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.

QFuture also offers ways to interact with a runnning computation. For instance, the computation can be canceled with the cancel() function. To pause the computation, use the setPaused() function or one of the pause(), resume(), or togglePaused() convenience functions. Be aware that not all running asynchronous computations can be canceled or paused. 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(), or isPaused() 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.

See also QFutureWatcher and Qt Concurrent.

Member Type Documentation

typedef QFuture::ConstIterator

Qt-style synonym for QFuture::const_iterator.

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.

bool QFuture::isPaused() const

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.

See also setPaused() and togglePaused().

template <typename U, typename> bool QFuture::isResultReadyAt(int index) const

Returns true if the result at index is immediately available; otherwise returns false.

See also resultAt() and resultCount().

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.

void QFuture::pause()

Pauses the asynchronous computation represented by this future. This is a convenience method that simply calls setPaused(true).

See also resume().

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).

See also resultAt() and results().

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.

See also result(), results(), 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(), and results().

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.

See also result(), resultAt(), and resultCount().

void QFuture::resume()

Resumes the asynchronous computation represented by this future. This is a convenience method that simply calls setPaused(false).

See also pause().

void QFuture::setPaused(bool paused)

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 isPaused(), pause(), resume(), and togglePaused().

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. When the asynchronous computation represented by this future finishes, function will be invoked in the same thread in which this future has been running. A new QFuture representing the result of the continuation is returned.

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> parentFuture = ...;
auto continuation = parentFuture.then([](int res1){ ... }).then([](int res2){ ... })...
...
// parentFuture 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 the parent future gets canceled, its continuations will also be canceled.

This function was introduced in Qt 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 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<int> 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<int> future = ...;
future.then(QtFuture::Launch::Async, [](int res){ ... })
      .then(QtFuture::Launch::Inherit, [](int res2){ ... });

This function was introduced in Qt 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.

void QFuture::togglePaused()

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()).

See also setPaused(), pause(), and resume().

void QFuture::waitForFinished()

Waits for the asynchronous computation to finish (including cancel()ed computations).

T QFuture::operator T() 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 result() or resultAt(0).

See also result(), resultAt(), and results().

bool QFuture::operator!=(const QFuture<T> &other) const

Returns true if other is not a copy of this future; otherwise returns false.

bool QFuture::operator==(const QFuture<T> &other) const

Returns true if other is a copy of this future; otherwise returns false.

© 2020 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.