c++ - 与 std::future 关联的存储是如何分配的?

标签 c++ asynchronous c++11 future c++-standard-library

获得 std::future 的一种方法是通过 std::async:

int foo()
{
  return 42;
}

...

std::future<int> x = std::async(foo);

在这个例子中,x 的异步状态的存储是如何分配的,哪个线程(如果涉及多个线程)负责执行分配?此外,std::async 的客户端是否可以控制分配?

对于上下文,我看到 one of the constructors std::promise 可能会收到一个分配器,但我不清楚是否可以在 级别自定义 std::future 的分配>std::async.

最佳答案

内存由调用std::async的线程分配,你无法控制它是如何完成的。通常,它将由 new __internal_state_type 的某些变体完成, 但不能保证;它可能会使用 malloc ,或为此目的专门选择的分配器。

从 30.6.8p3 [futures.async] 开始:

"Effects: The first function behaves the same as a call to the second function with a policy argument of launch::async | launch::deferred and the same arguments for F and Args. The second function creates a shared state that is associated with the returned future object. ..."

“第一个函数”是没有启动策略的过载,而第二个是有启动策略的过载。

std::launch::deferred的情况下,没有其他线程,所以一切都必须发生在调用线程上。在std::launch::async的情况下, 30.6.8p3 继续说:

— if policy & launch::async is non-zero — calls INVOKE (DECAY_COPY (std::forward<F>(f)), DECAY_COPY (std::forward<Args>(args))...) (20.8.2, 30.3.1.2) as if in a new thread of execution represented by a thread object with the calls to DECAY_COPY () being evaluated in the thread that called async. ...

我添加了重点。由于函数和参数的复制必须发生在调用线程中,这实质上要求共享状态由调用线程分配。

当然,您可以编写启动新线程的实现,等待它分配状态,然后返回 future。那引用了那个,但你为什么要这样做?

关于c++ - 与 std::future 关联的存储是如何分配的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12834281/

相关文章:

c++ - 为什么我需要在 move 构造函数的初始化列表中使用 std::move?

c++ - 如何使 C++ lambda 对象的存储更高效?

c++ - 如何在 WinDbg 扩展中基于转储文件内存创建对象?

django - 如何将 Django post_save 信号作为后台进程运行?

c# - 编码字符 *

.net - 异步与同步套接字

c# - Entity Framework 中的异步等待支持?

c++ - 通用引用参数使用了两次

c++ - 在 C++ 中将 if、else if、else 语句转换为 switch 语句

c++ - 带有 C++ 图形引擎的 Android NDK