async与future
当我们需要开启一个异步任务并在之后某个时刻获取结果时,可以使用std::async,其参数类似std::thread,但是它返回的是一个future对象,最终将包含任务执行的结果。在需要获取异步结果的地方,调用std::future::get,该方法将阻塞直到进入ready状态并返回结果
复制代码
1
2
3
4std::future<int> the_answer=std::async(find_the_answer_to_ltuae); do_other_stuff(); std::cout<<"The answer is "<<the_answer.get()<<std::endl;
std::async默认实现上允许直接开启新线程执行任务或者等到future::get/future::wait时才执行任务,我们可以添加一个std::launch参数显示指明要使用哪种方式执行新任务
- std::launch::deferred表明任务将在future::get或者future::wait时执行(同一线程)
- std::launch::async表明任务必须在新线程执行
- std::launch::deferred | std::launch::async等价于不指定执行方式,使用async默认实现
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18#include <future> #include <iostream> #include <Windows.h> using namespace std; int add(int a, int b) { cout << "work thread" << this_thread::get_id() << endl; Sleep(3000); return a + b; } int main() { cout << "main thread" << this_thread::get_id() << endl; future<int> result = async(launch::deferred, add, 2, 3);//1 Sleep(3000); cout << result.get() << endl; }
程序执行将耗费6秒,因为get被调用时add才会被执行。如果1处换成launch::async,则程序执行耗费3秒,因为在1处已经创建新线程执行add。
最后
以上就是负责含羞草最近收集整理的关于C++-std::async与std::future基本使用async与future的全部内容,更多相关C++-std内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复