Cor*_*mer 5 c++ multithreading future c++11
当启动策略设置为创建线程时std::launch::async,cppreference上给出的描述是
启动新线程以异步执行任务
如果我有一些任意的功能
double Foo(double i)
{
return i * 5.0;
}
Run Code Online (Sandbox Code Playgroud)
我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));
}
Run Code Online (Sandbox Code Playgroud)
当我这样打电话时std::accumulate:
double total = std::accumulate(begin(answers),
end(answers),
0.0,
[](double x, std::future<double>& t){return x + t.get();});
Run Code Online (Sandbox Code Playgroud)
什么时候每个线程开始执行?他们一加入就开始了answers吗?或者他们等到他们get被调用?如果是这样,我是否只是强制它们按顺序执行,因为它们get是按执行顺序调用的accumulate?换句话说,我是否只是浪费时间设置这些未来,然后强迫它们同步运行?
注意
该函数Foo只是一些例子,我正在使用的实际函数做了更多工作.
实际上,它们在您创建future. 它可能只被安排执行,或者实际上可能在调用返回之前启动async。
可能会尝试通过线程池等方式一次仅运行一定数量的线程(至少在最初),但这是实现质量问题,并且在不更具侵入性或要求被调用者提供更多信息的情况下正确实现这一点功能很难。
该标准没有强制要求任何接近该级别的行为,但实际上,异步实际上是异步的。