async概述
std::async() 是一个接受回调(函数或函数对象)作为参数的函数模板,并有可能异步执行它们.
std::async返回一个 std::future < T >,它存储由 std::async()执行的函数对象返回的值。
std::launch 中两个标志位会影响async实现方式
1、launch::async
异步任务:
#include <thread>
#include <iostream>
#include <future>
using namespace std;
int mythread()
{
cout << "mythread start ,id=" << this_thread::get_id() << endl;
this_thread::sleep_for(3s); //睡眠3s
cout << "mythread end ,id=" << this_thread::get_id() << endl;
return 5;
}
int main()
{
future<int> result = async(launch::async, mythread);
//创建异步任务并绑定future,
//launch::async相当于创建异步线程
int res = result.get(); //get()会阻塞等待异步任务完成
cout << res << endl;
return 0;
}
测试结果
2、launch::deferred
同步延时任务:
#include <thread>
#include <iostream>
#include <future>
using namespace std;
int mythread()
{
cout << "mythread start ,id=" << this_thread::get_id() << endl;
this_thread::sleep_for(3s);
cout << "mythread end ,id=" << this_thread::get_id() << endl;
return 5;
}
int main()
{
cout << "main start ,id=" << this_thread::get_id() << endl;
future<int> result = async(launch::deferred, mythread);
//创建延时任务,会等待get()调用才会开始此任务
//不创建线程,属于同步任务
this_thread::sleep_for(100ms);
cout << "result.get();" << endl;
int res = result.get(); //get()开启延时任务
cout << res << endl;
return 0;
}
测试结果如下:注意id相同,并没有创建线程
3、launch::async | launch::deferred
有了这个启动策略,它可以异步运行或不运行,这取决于系统的负载,即系统资源不够创建一个新线程时,那么就创建一个同步任务(deferred)。
从源代码可以看出这一参数也是默认参数。
template <class _Fty, class... _ArgTypes>
_NODISCARD future<_Invoke_result_t<decay_t<_Fty>, decay_t<_ArgTypes>...>> async(_Fty&& _Fnarg, _ArgTypes&&... _Args) {
// manages a callable object launched with default policy
return _STD async(launch::async | launch::deferred, _STD forward<_Fty>(_Fnarg), _STD forward<_ArgTypes>(_Args)...);
}
代码实现:
#include <thread>
#include <iostream>
#include <future>
using namespace std;
int mythread()
{
cout << "mythread start ,id=" << this_thread::get_id() << endl;
this_thread::sleep_for(3s);
cout << "mythread end ,id=" << this_thread::get_id() << endl;
return 5;
}
int main()
{
cout << "main start ,id=" << this_thread::get_id() << endl;
future<int> result = async(launch::deferred | launch::async, mythread);
//future<int> result = async( mythread); //默认参数同上
future_status status = result.wait_for(0s); //等待0s马上判断任务状态(同步或异步)
//可以通过status来判断任务状态
if (status == future_status::ready)
{
cout << "任务已执行完毕" << endl;
cout << result.get() << endl;
}
else if (status == future_status::deferred)
{
cout << "延时任务开启" << endl;
cout << result.get() << endl;
}
else if (status == future_status::timeout)
{
cout << "任务还未执行完毕" << endl;
cout << result.get() << endl;
}
return 0;
}
测试结果如下: