c++ - 如何理解 "std::future shared state"?

标签 c++ c++11

根据文档(http://www.cplusplus.com/reference/future/future/get/),它说: [强调我的]

Once the shared state is ready, the function unblocks and returns (or throws) releasing its shared state. This makes the future object no longer valid: this member function shall be called once at most for every future shared state.

根据文档(http://www.cplusplus.com/reference/future/future/),它说: [强调我的]

"Valid" futures are future objects associated to a shared state, and are constructed by calling one of the following functions

async

promise::get_future

packaged_task::get_future

根据文档(http://www.cplusplus.com/reference/future/future/get/),它说: [强调我的]

std::future::get

generic template (1) T get(); reference

specialization (2) R& future::get(); // when T is a reference

type (R&) void specialization (3) void future::get(); // when T is void

返回:

value Generally (1), std::move(x), where x is the value stored in the shared state.

For references (2), a reference to the value stored in the shared state.

For void futures (3), nothing.

我的问题是什么是“std::future 共享状态”?我如何理解“std::future 共享状态”?

我是C++的新手,想了又想,还是领悟不到思路。如果能为这个问题提供一些帮助,我将不胜感激。

最佳答案

根据cppreference std::future 的文档:

When the asynchronous operation is ready to send a result to the creator, it can do so by modifying shared state (e.g. std::promise::set_value) that is linked to the creator's std::future.

这里的共享状态指的是一些多线程可读/可写的可变内容。考虑直接来自文档的示例:

std::promise<int> p;
std::future<int> f = p.get_future();
std::thread([&p]{ p.set_value_at_thread_exit(9); }).detach();
f.wait();

主线程和创建的线程共享p(因为p是有状态的,它们共享状态!)。在 lambda 主体内调用 std::promise::set_value_at_thread_exit 有效地修改了这两个线程之间的共享状态。这基本上就是所有的意思。

promise 给出的 std::future 表示共享状态的“有趣”部分——您关心的值。

关于c++ - 如何理解 "std::future shared state"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62241240/

相关文章:

c++ - C++ 失败的空输入变量

c++ - g++ 4.7.2 用于类型别名的处理似乎被打破

c++ - 创建一个计时器以在 X 秒内调用一个函数

c++ - 在 C++ 中调用 system() 的问题

c++ - 通用引用忽略顶级简历限定符

C++: "this"指针没用吗?

c++ - 邻接表实现

c++ - 以下哪种方法可以安全地导出到 C++ dll 中?

c++ - 常量方法指针的类型是什么?

shared-ptr - shared_ptr<> 不需要使用引用计数吗?