以后如何修改std::async的std::launch策略? 我想在我的C++代码中使用 STD::AsYNC/并行运行一个计算重的函数 FUNC。现在,由于它是一个繁重的函数,我们可能首先对它使用std::launch::deferred策略,因为情况是我们可能根本不需要运行它
但是,如果将来我们需要突然执行它们,我们希望并行运行。那么我们以后如何修改以后如何修改std::async的std::launch策略? 我想在我的C++代码中使用 STD::AsYNC/并行运行一个计算重的函数 FUNC。现在,由于它是一个繁重的函数,我们可能首先对它使用std::launch::deferred策略,因为情况是我们可能根本不需要运行它,c++,asynchronous,parallel-processing,c++14,launch,C++,Asynchronous,Parallel Processing,C++14,Launch,但是,如果将来我们需要突然执行它们,我们希望并行运行。那么我们以后如何修改std::launch策略呢 [好吧,我们可以说,为什么不在需要执行时突然创建std::asyncs呢。但是我在这里假设我不能这样做。] 或者,除了使用std::async,还有什么更好更干净的方法来实现这一点吗 非常感谢您的帮助。提前谢谢 #include <future> #include <vector> #include <algorithm> #include <cstd
std::launch
策略呢
[好吧,我们可以说,为什么不在需要执行时突然创建std::async
s呢。但是我在这里假设我不能这样做。]
或者,除了使用std::async
,还有什么更好更干净的方法来实现这一点吗
非常感谢您的帮助。提前谢谢
#include <future>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <iostream>
std::vector<double> func(size_t n) // a computationally heavy function
{
std::vector<double> vec(n);
std::generate_n(vec.begin(), n, std::rand);
return vec;
}
int main()
{
// create asyncs, now deferred for lazy execution
auto v1 = std::async(std::launch::deferred, func, 200); // deferred for lazy execution
auto v2 = std::async(std::launch::deferred, func, 250); // deferred for lazy execution
// only after sometime we decide to execute both of them
// but we also now want them to execute in parallel
// so how can we now change the launch policy?
// to get the values as quickly as can be
auto n1 = v1.get().size();
auto n2 = v2.get().size();
std::cout<<"Got "<<n1<<" and "<<n2<<" random numbers in parallel!"<<std::endl;
return 0;
}
#包括
#包括
#包括说
它在调用线程上执行
然后,异步的概念就被破坏了,对吗?如果std::async
使用std::launch::deferred
,那么它将在调用返回的std::future
对象的get()
函数时运行
这表明您可以像这样强制std::launch::async
:
int s1 = 0;
int s2 = 0;
auto v1 = std::async(std::launch::deferred, []{ return 1; });
auto v2 = std::async(std::launch::deferred, []{ return 2; });
// some fancy coding ...
if(need_to_upgrade_launch_policy())
{
auto v1a = std::async(std::launch::async, [&]{ return v1.get(); });
auto v2a = std::async(std::launch::async, [&]{ return v2.get(); });
s1 = v1a.get();
s2 = v2a.get();
}
// more clever coding ...
if(v1.valid()) // was never upgraded
s1 = v1.get();
if(v2.valid()) // was never upgraded
s2 = v2.get();
为您的启动策略使用变量?@Galik:那么我如何使用它?等等,在创建std::async
对象后是否要更改午餐策略?我认为(目前)这不是使用标准STL。如果使用“延迟”创建异步,则在调用get()之前,它不会启动,因此您可以调用get()“just”来启动计算。@ffslq:async
是一个满足简单需求的简单工具。如果您的需求更复杂,那么您应该构建一个满足这些需求的工具,而不是依赖async
。这些工具不应该是[&]{return v1.get();})
和[&]{return v2.get();})
?好像它在工作。谢谢。但我们现在仍然在创建另外两个std::async
s。无论如何,这似乎是唯一的方法。@ffslq是的,我更新了示例以返回值。