首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++ broken_promise异常

C++ broken_promise异常
EN

Stack Overflow用户
提问于 2020-06-07 05:40:05
回答 1查看 313关注 0票数 1

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

但是,下面的示例代码似乎不会导致破坏承诺异常。我的理解是,当承诺被摧毁而未来仍在等待时,应该抛出异常。然而,在我的代码中,对future.get()的调用将永远等待。

是否应该调用promise的析构函数&在lambda完成时抛出异常?

代码语言:javascript
复制
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;
}

或者甚至是这个程序,在这个程序中,孩子们期望设定一个承诺

代码语言:javascript
复制
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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-07 06:11:21

主要的问题是错误的未来被等待着。

你在等待

代码语言:javascript
复制
int childValue = fut.get();

当你应该等待的时候

代码语言:javascript
复制
int childValue = retFut.get();

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62238337

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档