c++ - 与 std::future::unwrap 竞争异常传播

标签 c++ promise future race-condition c++20

关于 std::future 的 API 改进的论文在这里 n3721 .关于未包装的 future ,异常传播似乎存在竞争。文件说

If the outer future throws an exception, and .get() is called on the returned future, the returned future throws the same exception as the outer future. This is the case because the inner future didn’t exit

所以我的意思是像下面这样的情况

#include <iostream>
#include <future>
#include <exception>

using namespace std;

int main() {
    auto prom_one = std::promise<std::future<int>>{};
    auto fut_one = prom_one.get_future();

    std::thread{[prom_one = std::move(prom_one)]() mutable {
        auto prom_two = std::promise<int>{};
        auto fut_two = prom_two.get_future();
        std::thread{[prom_two = std::move(prom_two)]() mutable {
            prom_two.set_exception(std::make_exception_ptr(std::logic_error{}));
        }}.detach();
        prom_one.set_exception(std::make_exception_ptr(std::bad_alloc{}));
    }}.detach();


    auto inner_fut = fut_one.unwrap();
    cout << inner_fut.get() << endl;

    return 0;
}

我之前谈到的竞赛是——将抛出哪个异常?内部 std::logic_error 还是外部 std::bad_alloc

我是不是理解错了?上面的代码没有race吗?

最佳答案

我意识到上面的代码没有任何竞争,因为有一个嵌套的 future - std::future<std::future<int>>只有两种可能性,要么通过调用 std::promise::set_value 来设置内部 future 。或者已经设置了一个异常(exception),并且内部 future 与外部 future 根本没有联系(如上面的代码所示)。

如果内部 future 尚未链接,则外部 future 的异常将是抛出的异常。如果内在的 future 已经被链接起来,那么外在的 future 就没有范围了,因为外在的 future 的 promise 已经调用了set_value。与内部 future 一次,因此在外部 future 本身之后设置异常是无效的(这将导致异常本身被抛出)。

我想这就是论文说的时候说的

This is the case because the inner future didn’t exit

关于c++ - 与 std::future::unwrap 竞争异常传播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43942001/

相关文章:

c++ - 在对象上调用非常量成员函数指针

javascript - 调用异步函数但同步返回结果

javascript - Node : Use Promises in Loop with Q

Dart:同一个 future 的多个等待

C++ 11 future_status::deferred 不工作

c++ - 无法释放由 C++ 中的 CreateFileMapping 和 MapViewOfFile 创建的共享内存

c++ - 网络浏览器中定义的 zlib gzip 无效响应 (c++)

c++ - 通过类中定义的指针调用类方法时的语法

javascript - Promise 状态是否有任何符号?

asynchronous - Flutter Future<dynamic> 与 Future<String> 子类型错误?