获得 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 forF
andArgs
. 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 — callsINVOKE (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 toDECAY_COPY ()
being evaluated in the thread that calledasync
. ...
我添加了重点。由于函数和参数的复制必须发生在调用线程中,这实质上要求共享状态由调用线程分配。
当然,您可以编写启动新线程的实现,等待它分配状态,然后返回 future
。那引用了那个,但你为什么要这样做?
关于c++ - 与 std::future 关联的存储是如何分配的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12834281/