QFuture 类

template <typename T> class QFuture

QFuture 类表示异步计算的结果。 更多...

头: #include <QFuture>
CMake: find_package(Qt6 COMPONENTS Core REQUIRED)
target_link_libraries(mytarget PRIVATE Qt6::Core)
qmake: QT += core

注意: 此类的所有函数 thread-safe 除以下外:

公共类型

class const_iterator
  ConstIterator

公共函数

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

详细描述

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 () 和 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 提供 Java 风格迭代器 ( QFutureIterator ) 和 STL 样式迭代器 ( 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 () 或 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.

注意: Block 2 is invoked and throws an exception, the following onFailed () ( Block 3 ) will handle it. If the order of onFailed () 和 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
});
					

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 running 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 (),或 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 (),和 progressText () 函数。 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 () 或 isSuspended () 函数。

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 .

还可以使用 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 .

注意: To start a computation and store results in a QFuture, use QPromise or one of the APIs in the Qt Concurrent 框架。

另请参阅 QPromise , QtFuture::connect (), QtFuture::makeReadyFuture (), QtFuture::makeExceptionalFuture (), QFutureWatcher ,和 Qt Concurrent .

成员类型文档编制

QFuture:: ConstIterator

Qt 样式同义词 QFuture::const_iterator .

成员函数文档编制

QFuture:: QFuture (const QFuture < T > & other )

构造副本为 other .

另请参阅 operator= ().

QFuture:: QFuture ()

构建空的被取消 Future。

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

赋值 other to this future and returns a reference to this future.

QFuture:: ~QFuture ()

销毁 Future。

Note that this neither waits nor cancels the asynchronous computation. Use waitForFinished () 或 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

返回常量 STL 样式迭代器 指向 Future 的第一个结果。

另请参阅 constBegin () 和 end ().

void QFuture:: cancel ()

Cancels the asynchronous computation represented by this future. Note that the cancellation is asynchronous. Use waitForFinished () 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 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

返回常量 STL 样式迭代器 指向 Future 的第一个结果。

另请参阅 begin () 和 constEnd ().

template <typename U, typename> QFuture::const_iterator QFuture:: constEnd () const

返回常量 STL 样式迭代器 pointing to the imaginary result after the last result in the future.

另请参阅 constBegin () 和 end ().

template <typename U, typename> QFuture::const_iterator QFuture:: end () const

返回常量 STL 样式迭代器 pointing to the imaginary result after the last result in the future.

另请参阅 begin () 和 constEnd ().

bool QFuture:: isCanceled () const

返回 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 。见 cancel () 了解更多细节。

bool QFuture:: isFinished () const

返回 true if the asynchronous computation represented by this future has finished; otherwise returns false .

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

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

注意: Calling isResultReadyAt() leads to undefined behavior if isValid () 返回 false for this QFuture .

另请参阅 resultAt (), resultCount (),和 takeResult ().

bool QFuture:: isRunning () const

返回 true if the asynchronous computation represented by this future is currently running; otherwise returns false .

bool QFuture:: isStarted () const

返回 true if the asynchronous computation represented by this future has been started; otherwise returns false .

[since 6.0] bool QFuture:: isSuspended () const

返回 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.

该函数在 Qt 6.0 引入。

另请参阅 setSuspended (), toggleSuspended (),和 isSuspending ().

[since 6.0] bool QFuture:: isSuspending () const

返回 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 否则。

To check if suspension is actually in effect, use isSuspended () 代替。

该函数在 Qt 6.0 引入。

另请参阅 setSuspended (), toggleSuspended (),和 isSuspended ().

[since 6.0] bool QFuture:: isValid () const

返回 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.

该函数在 Qt 6.0 引入。

另请参阅 takeResult (), result (), results (),和 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() .

该函数在 Qt 6.0 引入。

另请参阅 then () 和 onFailed ().

[since 6.1] template <typename Function, typename> QFuture < T > QFuture:: onCanceled ( QObject * context , 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 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.

该函数在 Qt 6.1 引入。

另请参阅 then () 和 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 语句。

例如:

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
}
					

注意: You can always attach a handler taking no argument, to handle all exception types and avoid writing the try-catch block.

该函数在 Qt 6.0 引入。

另请参阅 then () 和 onCanceled ().

[since 6.1] template <typename Function, typename> QFuture < T > QFuture:: onFailed ( QObject * context , Function && handler )

这是重载函数。

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.

注意: When calling this method, it should be guaranteed that the context stays alive throughout the execution of the chain.

该函数在 Qt 6.1 引入。

另请参阅 then () 和 onCanceled ().

int QFuture:: progressMaximum () const

返回最大 progressValue ().

另请参阅 progressValue () 和 progressMinimum ().

int QFuture:: progressMinimum () const

返回最小 progressValue ().

另请参阅 progressValue () 和 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

返回当前进度值,位于 progressMinimum () 和 progressMaximum ().

另请参阅 progressMinimum () 和 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 () 代替。

注意: 调用 result() leads to undefined behavior if isValid () 返回 false for this QFuture .

另请参阅 resultAt (), results (),和 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.

注意: Calling resultAt() leads to undefined behavior if isValid () 返回 false for this QFuture .

另请参阅 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().

另请参阅 result (), resultAt (), results (),和 takeResult ().

template <typename U, typename> QList < T > QFuture:: 结果 () 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 样式迭代器 or read-only Java 风格迭代器 .

注意: 调用 results() leads to undefined behavior if isValid () 返回 false for this QFuture .

另请参阅 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).

另请参阅 suspend ().

[since 6.0] void QFuture:: setSuspended ( bool suspend )

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.

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.

该函数在 Qt 6.0 引入。

另请参阅 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)。

该函数在 Qt 6.0 引入。

另请参阅 resume ().

[since 6.0] template <typename U, typename> T QFuture:: takeResult ()

Call this function only if isValid () 返回 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 样式迭代器 or read-only Java 风格迭代器 .

该函数在 Qt 6.0 引入。

另请参阅 result (), results (), resultAt (),和 isValid ().

[since 6.0] template <typename Function> QFuture < ResultType < Function > > QFuture:: then ( Function && 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.

注意: 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){ ... })...
					

或:

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.

注意: If this future gets canceled, the continuations attached to it will also be canceled.

该函数在 Qt 6.0 引入。

另请参阅 onFailed () 和 onCanceled ().

[since 6.0] template <typename Function> QFuture < ResultType < Function > > QFuture:: then ( QtFuture::Launch policy , Function && 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){ ... });
					

该函数在 Qt 6.0 引入。

另请参阅 onFailed () 和 onCanceled ().

[since 6.0] template <typename Function> QFuture < ResultType < Function > > QFuture:: then ( QThreadPool * pool , Function && 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 .

该函数在 Qt 6.0 引入。

另请参阅 onFailed () 和 onCanceled ().

[since 6.1] template <typename Function> QFuture < ResultType < Function > > QFuture:: then ( QObject * context , Function && 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.

注意: When calling this method, it should be guaranteed that the context stays alive throughout the execution of the chain.

该函数在 Qt 6.1 引入。

另请参阅 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 ())).

该函数在 Qt 6.0 引入。

另请参阅 setSuspended (), suspend (),和 resume ().

void QFuture:: waitForFinished ()

Waits for the asynchronous computation to finish (including cancel ()ed computations), i.e. until isFinished () 返回 true .