后来,我如何修改STD ::启动策略的STD :: async
How can I modify the std::launch policy afterwards for std::async?
假设我想在我的C 代码中使用std::async
进行并行性来运行计算重函数func
。现在由于它是一个重型功能,我们可能首先使用std::launch::deferred
策略,因为情况是我们可能不需要运行。
但是,如果我们再一次需要执行它们,将来,我们希望并行运行。然后,如何修改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::launch::deferred
定义std::async
后,当人们调用.get()
函数时,将保证运行 async (即并行(,而不是。http://en.cppreference.com/w/cpp/thread/launch说
它是在调用线程上执行的。
那么 async 的概念被宠坏了,对吗?
如果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();
相关文章:
- 使用 std::string () const 函数启动线程或未来
- 如何默认启动 std::vector
- Cuda 基本程序 (将值写入矩阵和 std:cout 不起作用) ;主功能不启动
- 在没有复制构造函数的对象的成员函数中启动 std::thread
- 使用 std::thread & std::bind 在成员函数中启动线程
- 使用 std::vector<std::future<int>> 和 std::async 启动几个线程时中止
- std::thread从函数启动,无需等待线程完成
- 从 VS2013 到 VS2017 std::async 不会启动新线程
- 线程是否真的在调用 std::future::get() 后启动
- 后来,我如何修改STD ::启动策略的STD :: async
- 标准C++11是否保证std::async(std::launch::asyncfunc)在单独的线程中启动func
- 通过 std::async 启动的函数引发的异常会发生什么情况
- std::async在指定启动::async时未执行
- std::启动服务器时发生异常(WinSock2)
- std::async不使用std::launch::async策略启动新线程
- 启动 std::thread 时无法将(函数指针)左值绑定到(函数指针)右值
- 默认启动策略和std::launch::deferred之间的区别
- std::thread,在"this"上启动线程(从类本身内部)
- C++ 游戏启动终止在抛出"std::out_of_range"实例后调用
- 使用静态链接启动std::线程会导致分段错误