本页内容

QPromise Class

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
自: Qt 6.0

注意:该类中的所有函数均是线程安全的。

公共函数

QPromise()
QPromise(const QPromise<T> &)
QPromise(QPromise<T> &&other)
~QPromise()
bool addResult(T &&result, int index = -1)
bool addResult(const T &result, int index = -1)
(since 6.6) bool addResults(const QList<T> &results)
(since 6.6) bool emplaceResult(Args &&... args)
(since 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<T> &operator=(const QPromise<T> &)

详细说明

QPromise 是一个模板类,其中模板参数T 指定了结果类型,该类型可以被存储,并可通过QFuture 随后访问。

QPromise 提供了一种简单的方法,可以以异步方式将用户定义计算的进度和结果传达给 `QFuture `。为了使通信正常工作,必须由 QPromise 来构造 `QFuture `。

当需要精细控制时,您可以使用基于 QPromise 的工作负载作为 Qt Concurrent 当需要精细控制,或者仅需配合QFuture 使用的高级通信原语时,可采用基于 QPromise 的工作负载。

Promise 与 Future 协作的最简单情况就是单结果通信:

    QPromise<int> promise;
    QFuture<int> future = promise.future();

    const std::unique_ptr<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

按设计,QPromise 是一个仅允许移动的对象。这种行为有助于确保:每当 Promise 被销毁时,关联的 Future 对象都会收到通知,从而避免无限期等待结果。然而,如果希望使用同一个 Promise 来报告来自不同线程的结果,这种设计就会带来不便。 目前尚无专门的方法实现这一点,但已有已知的机制,例如使用智能指针或原始指针/引用。若您希望复制一个 Promise 并同时在多处使用它,QSharedPointer 是一个不错的默认选择。 从某种意义上说,原始指针或引用更简单,而且性能可能更好(因为无需进行资源管理),但可能会导致悬空指针。

以下是一个在多个线程中使用 Promise 的示例:

    const auto sharedPromise = std::make_shared<QPromise<int>>();
    QFuture<int> future = sharedPromise->future();

    // ...

    sharedPromise->start();

    // here, QPromise is shared between threads via a smart pointer
    const std::unique_ptr<QThread> threads[] = {
        std::unique_ptr<QThread>(QThread::create([] (auto sharedPromise) {
            sharedPromise->addResult(0, 0);  // adds value 0 by index 0
        }, sharedPromise)),
        std::unique_ptr<QThread>(QThread::create([] (auto sharedPromise) {
            sharedPromise->addResult(-1, 1);  // adds value -1 by index 1
        }, sharedPromise)),
        std::unique_ptr<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 。

成员函数文档

[default] QPromise::QPromise()

创建一个具有默认状态的 QPromise。

[delete] QPromise::QPromise(const QPromise<T> &)

复制并构造一个QPromise 实例。该函数已被删除。

[default] QPromise::QPromise(QPromise<T> &&other)

Move 根据 `other` 构建一个新的 `QPromise`。

另请参阅 operator=()。

QPromise::~QPromise()

销毁该 Promise。

注意: 除非用户事先调用了finish(),否则该 Promise 在被销毁时会隐式地过渡到已取消的状态。

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

或者,如果index == -1 (默认值)

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

另请参阅 emplaceResultAt()、emplaceResult() 和addResults()。

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

将 `results ` 添加到内部结果集合的末尾。

当向集合中添加results 时,返回true 。

当此 Promise 处于已取消或已完成状态时,返回false 。

这比遍历addResult() 更高效,因为关联的未来对象仅会在每次 addResults() 调用时被通知一次,而不是像单独调用addResult() 那样,针对results 中包含的每个元素分别通知一次。 但如果每个元素的计算都需要时间,那么接收端(Future)的代码将无法继续执行,直到所有结果都被报告为止,因此仅当连续元素的计算速度相对较快时,才应使用此函数。

该函数于 Qt 6.6 中引入。

另请参阅 addResult()。

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

将一个由args... 构建的结果添加到内部结果集合中,位置为index (emplaceResultAt ())或集合末尾(emplaceResult ())。

当结果被添加到集合中时,返回true 。

当此 Promise 处于已取消或已完成状态,或者结果被拒绝时,返回false 。如果集合中同一索引位置已存储另一个结果,addResult() 将拒绝添加该结果。

这些函数仅在T 可由args....

您可以通过调用QFuture::resultAt() 获取特定索引处的结果。

注意:可以 指定任意索引并获取该索引处的结果。但是,某些 `QFuture ` 方法处理的是连续的结果。例如,使用 `QFuture::resultCount()` 或 `QFuture::const_iterator` 的迭代方法。为了获取所有可用结果而无需考虑是否存在索引缺口,请使用 `QFuture::results()`。

这些函数在 Qt 6.6 中引入。

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

void QPromise::finish()

报告计算已完成。计算完成后,调用addResult() 时将不再添加新结果。该方法与start() 配合使用。

另请参阅 QFuture::isFinished()、QFuture::waitForFinished() 和start()。

QFuture<T> QPromise::future() const

返回与该 Promise 关联的 Future。

bool QPromise::isCanceled() const

返回值表示计算是否已被通过QFuture::cancel()函数取消。返回值true 表示应完成计算并调用finish()。

注意:取消后 ,当前可用的结果仍可被后续操作访问,但在调用addResult() 时,不会添加新的结果。

void QPromise::setException(const QException &e)

将异常e 设置为计算结果。

注意: 在整个计算执行过程中,最多只能 设置一个异常。

注意: 在调用QFuture::cancel() 或finish() 之后,此方法 将不再生效。

另请参阅 isCanceled()。

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

这是一个重载函数。

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

将计算的进度范围设置为minimum 到maximum 之间。

如果maximum 小于minimum ,则minimum 成为唯一的有效值。

进度值将重置为minimum 。

可通过调用 setProgressRange(0, 0) 禁用进度范围功能。此时,进度值也会重置为 0。

另请参阅 QFuture::progressMinimum()、QFuture::progressMaximum() 和QFuture::progressValue()。

void QPromise::setProgressValue(int progressValue)

将计算的进度值设置为progressValue 。该方法仅支持递增进度值。这是调用setProgressValueAndText(progressValue, QString())的便捷方法。

如果progressValue 超出了进度范围,则此方法无效。

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

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

将计算的进度值和进度文本分别设置为progressValue 和progressText 。也可以仅递增进度值。

注意: 如果 Promise 处于已取消或已完成状态,此 函数将不起作用。

另请参阅 QFuture::progressValue()、QFuture::progressText()、QFuture::cancel() 和finish()。

void QPromise::start()

报告计算已开始。调用此方法对于声明计算的开始非常重要,因为QFuture 方法依赖于此信息。

注意: 当从新创建的线程中调用 start() 时,需格外 注意。在此情况下,由于线程调度的实现细节,该调用可能会自然地被延迟。

另请参阅 QFuture::isStarted()、QFuture::waitForFinished() 和finish()。

void QPromise::suspendIfRequested()

有条件地暂停当前执行线程,并等待直至被QFuture 的相应方法恢复或取消。除非通过QFuture::suspend()或其他相关方法请求暂停计算,否则该方法不会阻塞。若要检查执行是否已被暂停,请使用QFuture::isSuspended()。

注意:当在 多个线程中使用同一个 Promise时 ,只要至少有一个持有该 Promise 的线程被挂起,QFuture::isSuspended() 就会立即变为true 。

以下代码片段展示了暂停机制的使用方法:

    // Create promise and future
    QPromise<int> promise;
    QFuture<int> future = promise.future();

    promise.start();
    // Start a computation thread that supports suspension and cancellation
    const std::unique_ptr<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() 请求关联的 Promise 进入暂停状态:

    future.suspend();

当QFuture::isSuspended() 变为true 后,您可以获取中间结果:

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

暂停后,您可以恢复或取消正在等待的计算:

    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)

将该承诺与other 互换。此操作速度极快,且绝不会失败。

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

该操作将 `other ` 赋值给该 Promise,并返回对该 Promise 的引用。

[delete] QPromise<T> &QPromise::operator=(const QPromise<T> &)

将other 复制并赋值给此QPromise 实例。该函数已被删除。

© 2026 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.