QPromise 类

template <typename T> class QPromise

QPromise 类提供存储计算结果的办法,访问通过 QFuture . 更多...

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

注意: 此类的所有函数 thread-safe .

公共函数

QPromise ()
QPromise (QPromise<T> && other )
~QPromise ()
bool addResult (const T & result , int index = -1)
bool addResult (T && result , int index = -1)
(从 6.6 起) bool addResults (const QList<T> & 结果 )
(从 6.6 起) bool emplaceResult (Args &&... args )
(从 6.6 起) bool emplaceResultAt (int index , Args &&... args )
void finish ()
QFuture<T> future () const
bool isCanceled () const
void setException (const QException & e )
void setException (std::__exception_ptr::exception_ptr e )
void setProgressRange (int minimum , int maximum )
void setProgressValue (int progressValue )
void setProgressValueAndText (int progressValue , const QString & progressText )
void start ()
void suspendIfRequested ()
void swap (QPromise<T> & other )
QPromise<T> & operator= (QPromise<T> && other )

详细描述

QPromise provides a simple way to communicate progress and results of the user-defined computation to QFuture in an asynchronous fashion. For the communication to work, QFuture must be constructed by QPromise.

You can use QPromise based workloads as an alternative to Qt Concurrent framework when fine-grained control is needed or high-level communication primitive to accompany QFuture is sufficient.

The simplest case of promise and future collaboration would be a single result communication:

    QPromise<int> promise;
    QFuture<int> future = promise.future();
    QScopedPointer<QThread> thread(QThread::create([] (QPromise<int> promise) {
        promise.start();   // notifies QFuture that the computation is started
        promise.addResult(42);
        promise.finish();  // notifies QFuture that the computation is finished
    }, std::move(promise)));
    thread->start();
    future.waitForFinished();  // blocks until QPromise::finish is called
    future.result();  // returns 42
					

By design, QPromise is a move-only object. This behavior helps to ensure that whenever the promise is destroyed, the associated future object is notified and will not wait forever for the results to become available. However, this is inconvenient if one wants to use the same promise to report results from different threads. There is no specific way to do that at the moment, but known mechanisms exist, such as the use of smart pointers or raw pointers/references. QSharedPointer is a good default choice if you want to copy your promise and use it in multiple places simultaneously. Raw pointers or references are, in a sense, easier, and probably perform better (since there is no need to do a resource management) but may lead to dangling.

Here is an example of how a promise can be used in multiple threads:

    QSharedPointer<QPromise<int>> sharedPromise(new QPromise<int>());
    QFuture<int> future = sharedPromise->future();
    // ...
    sharedPromise->start();
    // here, QPromise is shared between threads via a smart pointer
    QScopedPointer<QThread> threads[] = {
        QScopedPointer<QThread>(QThread::create([] (auto sharedPromise) {
            sharedPromise->addResult(0, 0);  // adds value 0 by index 0
        }, sharedPromise)),
        QScopedPointer<QThread>(QThread::create([] (auto sharedPromise) {
            sharedPromise->addResult(-1, 1);  // adds value -1 by index 1
        }, sharedPromise)),
        QScopedPointer<QThread>(QThread::create([] (auto sharedPromise) {
            sharedPromise->addResult(-2, 2);  // adds value -2 by index 2
        }, sharedPromise)),
        // ...
    };
    // start all threads
    for (auto& t : threads)
        t->start();
    // ...
    future.resultAt(0);  // waits until result at index 0 becomes available. returns value  0
    future.resultAt(1);  // waits until result at index 1 becomes available. returns value -1
    future.resultAt(2);  // waits until result at index 2 becomes available. returns value -2
    sharedPromise->finish();
					

另请参阅 QFuture .

成员函数文档编制

bool QPromise:: addResult ( T && result , int index = -1)

bool QPromise:: addResult (const T & result , int index = -1)

如同

emplaceResultAt(index, result);            // first overload
emplaceResultAt(index, std::move(result)); // second overload
					

or, if index == -1 (the default)

emplaceResult(result);            // first overload
emplaceResult(std::move(result)); // second overload
					

另请参阅 emplaceResultAt (), emplaceResult (),和 addResults ().

[since 6.6] template <typename... Args, std::enable_if_t<std::is_constructible_v<T, Args...>, bool> = true> bool QPromise:: emplaceResult ( Args &&... args )

[since 6.6] template <typename... Args, std::enable_if_t<std::is_constructible_v<T, Args...>, bool> = true> bool QPromise:: emplaceResultAt ( int index , Args &&... args )

Adds a result constructed from args... to the internal result collection at index position ( emplaceResultAt ()) or the end of of the collection ( emplaceResult ()).

返回 true when the result was added to the collection.

返回 false when this promise is in canceled or finished state or when the result was rejected. addResult () rejects to add a result if there's already another result in the collection stored at the same index.

These functions only participate in overload resolutions if T is constructible from args....

You can get a result at a specific index by calling QFuture::resultAt ().

注意: It is possible to specify an arbitrary index and request result at that index. However, some QFuture methods operate with continuous results. For instance, iterative approaches that use QFuture::resultCount () 或 QFuture::const_iterator . In order to get all available results without thinking if there are index gaps or not, use QFuture::results ().

该函数在 Qt 6.6 引入。

另请参阅 addResult () 和 addResults ().

QPromise:: QPromise ()

Constructs a QPromise with a default state.

QPromise:: QPromise ( QPromise < T > && other )

Move constructs a new QPromise from other .

另请参阅 operator= ().

QPromise:: ~QPromise ()

Destroys the promise.

注意: The promise implicitly transitions to a canceled state on destruction unless finish () is called beforehand by the user.

[since 6.6] bool QPromise:: addResults (const QList < T > & 结果 )

添加 结果 at the end of the internal result collection.

返回 true 结果 are added to the collection.

返回 false when this promise is in canceled or finished state.

This is more efficient than looping over addResult (), because associated futures will be notified only once per addResults() call, instead of once per element contained in 结果 , as would be the case with individual addResult () calls. But if the calculation of each element takes time, then the code on the receiving end (future) cannot make progress until all results are reported, so use this function only if the calculation of consecutive elements is relatively fast.

该函数在 Qt 6.6 引入。

另请参阅 addResult ().

void QPromise:: finish ()

Reports that the computation is finished. Once finished, no new results will be added when calling addResult (). This method accompanies start ().

另请参阅 QFuture::isFinished (), QFuture::waitForFinished (),和 start ().

QFuture < T > QPromise:: future () const

Returns a future associated with this promise.

bool QPromise:: isCanceled () const

Returns whether the computation has been canceled with the QFuture::cancel () function. The returned value true indicates that the computation should be finished and finish () called.

注意: After cancellation, results currently available may still be accessed by a future, but new results will not be added when calling addResult ().

void QPromise:: setException (const QException & e )

Sets exception e to be the result of the computation.

注意: You can set at most one exception throughout the computation execution.

注意: This method must not be used after QFuture::cancel () 或 finish ().

另请参阅 isCanceled ().

void QPromise:: setException ( std::__exception_ptr::exception_ptr e )

这是重载函数。

void QPromise:: setProgressRange ( int minimum , int maximum )

Sets the progress range of the computation to be between minimum and maximum .

maximum 小于 minimum , minimum 变为唯一合法值。

The progress value is reset to be minimum .

The progress range usage can be disabled by using setProgressRange(0, 0). In this case progress value is also reset to 0.

另请参阅 QFuture::progressMinimum (), QFuture::progressMaximum (),和 QFuture::progressValue ().

void QPromise:: setProgressValue ( int progressValue )

Sets the progress value of the computation to progressValue . It is possible to only increment the progress value. This is a convenience method for calling setProgressValueAndText (progressValue, QString()).

In case of the progressValue falling out of the progress range, this method has no effect.

另请参阅 QFuture::progressValue () 和 setProgressRange ().

void QPromise:: setProgressValueAndText ( int progressValue , const QString & progressText )

Sets the progress value and the progress text of the computation to progressValue and progressText respectively. It is possible to only increment the progress value.

注意: This function has no effect if the promise is in canceled or finished state.

另请参阅 QFuture::progressValue (), QFuture::progressText (), QFuture::cancel (),和 finish ().

void QPromise:: start ()

Reports that the computation is started. Calling this method is important to state the beginning of the computation as QFuture methods rely on this information.

注意: Extra attention is required when start() is called from a newly created thread. In such case, the call might naturally be delayed due to the implementation details of the thread scheduling.

另请参阅 QFuture::isStarted (), QFuture::waitForFinished (),和 finish ().

void QPromise:: suspendIfRequested ()

Conditionally suspends current thread of execution and waits until resumed or canceled by the corresponding methods of QFuture . This method does not block unless the computation is requested to be suspended by QFuture::suspend () or another related method. If you want to check that the execution has been suspended, use QFuture::isSuspended ().

注意: When using the same promise in multiple threads, QFuture::isSuspended () becomes true as soon as at least one thread with the promise suspends.

The following code snippets show the usage of suspension mechanism:

    // Create promise and future
    QPromise<int> promise;
    QFuture<int> future = promise.future();
    promise.start();
    // Start a computation thread that supports suspension and cancellation
    QScopedPointer<QThread> thread(QThread::create([] (QPromise<int> promise) {
        for (int i = 0; i < 100; ++i) {
            promise.addResult(i);
            promise.suspendIfRequested();   // support suspension
            if (promise.isCanceled())       // support cancellation
                break;
        }
        promise.finish();
    }, std::move(promise)));
    thread->start();
					

QFuture::suspend () requests the associated promise to suspend:

    future.suspend();
					

后于 QFuture::isSuspended () becomes true , you can get intermediate results:

    future.resultCount();  // returns some number between 0 and 100
    for (int i = 0; i < future.resultCount(); ++i) {
        // process results available before suspension
    }
					

When suspended, you can resume or cancel the awaiting computation:

    future.resume();  // resumes computation, this call will unblock the promise
    // alternatively, call future.cancel() to stop the computation
    future.waitForFinished();
    future.results();  // returns all computation results - array of values from 0 to 99
					

另请参阅 QFuture::resume (), QFuture::cancel (), QFuture::setSuspended (),和 QFuture::toggleSuspended ().

[noexcept] void QPromise:: swap ( QPromise < T > & other )

Swaps promise other with this promise. This operation is very fast and never fails.

[noexcept] QPromise < T > &QPromise:: operator= ( QPromise < T > && other )

Move assigns other to this promise and returns a reference to this promise.