首页 > 解决方案 > C++ 破承诺异常

问题描述

我正在学习std::async并遇到broken_promise异常。

但是,以下示例代码似乎不会导致损坏的承诺异常。我的理解是,当promise被销毁,future还在等待的时候,应该抛出异常。但是,在我的代码中,调用future.get()会永远等待。

不应该调用 promise 的析构函数并在 lambda 完成时抛出异常吗?

int main()
{
    std::promise<int> prom;
    std::future<int> fut = prom.get_future();
    auto retFut = std::async(std::launch::async, [prom = std::move(prom)] () mutable {
        cout << "In child" << endl;
        //prom.set_value(4); <-- Shouldn't not having this line cause the exception
    });

    int childValue = fut.get();
    cout << "Child has set the value: " << childValue << endl;
    return 0;
}

甚至是这个孩子期望得到承诺的项目

void DoSomething(std::future<int>&& fut)
{
    cout << "Waiting for parent to send a value " << endl;
    int val = fut.get();

    cout << "Parent sent value " << val << endl;
}

int main()
{
    std::promise<int> prom;
    std::future<int> fut = prom.get_future();
    auto retFut = std::async(std::launch::async, DoSomething, std::move(fut));
    // prom.set_value(3); <-- This should cause the exception?
    return 0;
}

标签: c++

解决方案


主要问题是正在等待错误的未来。

你在等待

int childValue = fut.get();

当你应该等待时

int childValue = retFut.get();

话虽这么说,std::async是最好避开的 C++ 的一部分。在实践中,它很少交付,在复杂的项目中最好使用某种任务池,例如cpp-taskflow.


推荐阅读