std::future 什么时候执行?

When does std::future get executed?

创建线程时启动策略设置为std::launch::async, the description given on cppreference

a new thread is launched to execute the task asynchronously

如果我有一些任意函数

double Foo(double i)
{
    return i * 5.0;
}

然后我像这样设置了一个 async 调用

std::vector<double> values{5.0, 2.3, 7.1, 4.8, 1.5};
std::vector<std::future<double>> answers;
for (double value : values)
{
    answers.push_back(std::async(std::launch::async,
                                 Foo,
                                 value));
}

当我这样调用 std::accumulate 时:

double total = std::accumulate(begin(answers),
                               end(answers),
                               0.0,
                               [](double x, std::future<double>& t){return x + t.get();});

每个线程什么时候开始执行?他们一加入answers就开始了吗?还是等到 get 被调用?如果是这样,我是否只是强制它们按顺序执行,因为它们的 get 是按照 accumulate 执行它们的顺序调用的?换句话说,我只是在浪费时间设置这些期货,然后强制它们同步 运行 吗?

备注
函数 Foo 只是一些例子,我使用的实际函数做更多的工作。

只要您调用std::async,线程就会启动。因此,您的线程将 运行 并发。

引用cpp-reference:

If the async flag is set (i.e. policy & std::launch::async != 0), then async executes the function f on a new thread of execution (with all thread-locals initialized) as if spawned by std::thread(f, args...), except that if the function f returns a value or throws an exception, it is stored in the shared state accessible through the std::future that async returns to the caller.

实际上,它们会在您创建 future 时启动。它可能只被安排执行,或者实际上可能在调用 async returns.

之前启动

可能有人尝试通过线程池等方式一次(至少在最初)仅保留一定数量的线程 运行,但这是实现质量问题,如果没有很难从被调用函数中获得更多侵入性或要求更多。

该标准并未强制执行任何接近该级别的行为,但在实践中,异步实际上是异步的。