(1)std::async、std::future创建后台任务并返回
(2)std::packaged_task
(3)std::promise
(4)小结
一、std::async、std::future创建后台任务并返回
希望线程返回一个结果;
std::async是一个函数模板,用来启动一个异步任务,启动起来一个异步任务后,
他返回一个std::future对象,std::future是一个类模板
什么事是启动一个异步任务呀?
就是自动创建一个线程,并开始执行对应的线程入口函数,它返回一个
std::future对象,这个对象中含有线程函数返回的结果(线程返回的结果)。
可以通过std::future对象的成员函数get()来获取结果。
std::future提供了一种访问异步操作结果的机制,这个结果没办法马上获得,
但是在这个线程执行完的时候,就可以获取到结果了,future对象里保存一个值,就是这个结果、
#include <future>
#include <list>
#include <map>
#include <mutex>
#include <thread>
int thread_fun()//线程入口函数
{
cout<<"thread_fun start thread_id = "<<std::this_thread::get_id()<<endl;
std::chrono::milliseconds dura(5000);//休息5秒
std::this_thread::sleep_for(dura);//休息一定时长
cout<<"thread_fun end thread_id = "<<std::this_thread::get_id()<<endl;
return 5;
}
int main()
{
//下列程序std::future对象get()成员函数等待线程执行结果并返回结果
cout<<"main thread_id = "<<std::this_thread::get_id()<<endl;
std::future<int> result = std::async(thread_fun);//创建一个线程,并开始执行
绑定关系,流程不会卡在这里
cout<<"continue..."<<endl;
int def = 0;
cout<<result.get()<<endl;//会先卡在get()这里,一直等到thread_fun执行完成,获取到返回值,然后线程程序才会继续向下。
//result.wait();//等待线程返回,本身不返回结果;
cout<<"end ..."<<endl;
return 0;
}
class B
{
public:
int thread_fun(int my_mun)//线程入口函数
{
cout<<my_mun<<endl;
cout<<"thread_fun start thread_id = "<<std::this_thread::get_id()<<endl;
std::chrono::milliseconds dura(5000);//休息5秒
std::this_thread::sleep_for(dura);//休息一定时长
cout<<"thread_fun end thread_id = "<<std::this_thread::get_id()<<endl;
return 5;
}
}
int main()
{
A a1;
int mun=12;
//下列程序std::future对象get()成员函数等待线程执行结果并返回结果
cout<<"main thread_id = "<<std::this_thread::get_id()<<endl;
std::future<int> result = std::async(&A::thread_fun,&a,num);//创建一个线程,并开始执行
绑定关系,流程不会卡在这里
cout<<"continue..."<<endl;
int def = 0;
cout<<result.get()<<endl;//会先卡在get()这里,一直等到thread_fun执行完成,获取到返回值,然后线程程序才会继续向下。
//result.wait();//等待线程返回,本身不返回结果;
cout<<"end ..."<<endl;
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)