- 一、异步操作:std::async、std::future创建后台任务并返回值
- 同步异步:同步是让一个任务执行完了下一个任务才能开始,异步可近似认为同时在做
- std::async:是一个函数模板,用来启动一个异步任务,启动起来一个异步任务后,返回一个std::future对象
- 什么是启动一个异步任务:就是自动创建一个线程并开始执行对应的线程入口函数,返回一个std::future对象,这个返回一个std::future对象里含有入口函数返回的结果(线程返回值)
- 在线程执行完毕后,通过future的成员函数get()可获取结果,get()函数如果不拿到线程返回值,就一直卡在这
- wait():等待线程返回,不需要结果
- std::lauch::deferred:延迟调用,直到遇到get()或者wait()才会调用线程入口函数,但并没有新建线程,是在主线程调用的线程入口函数
- std::launch::async:不需要遇到get()就能执行线程入口函数,并且新建线程,实现异步操作
- 二、std::promise类模板
线程间通信,在某个线程中对它赋值,在另一个线程读取它的值;
#include <thread>
#include <mutex>
#include <future>
#include <iostream>
using namespace std;
int myThread()
{
cout<<"My thread start,thread_id= "<<std::this_thread::get_id()<<endl;
std::this_thread::sleep_for(std::chrono::seconds(3));
cout<<"My thread is over,thread_id= "<<std::this_thread::get_id()<<endl;
return 5;
}
void myThread2(std::promise<int> &tmp,int num)
{
cout<<"My thread start,thread_id= "<<std::this_thread::get_id()<<endl;
num+=1;
tmp.set_value(num);
cout<<"My thread is over,thread_id= "<<std::this_thread::get_id()<<endl;
}
void myThread3(std::future<int> &tmp)
{
cout<<"My thread start,thread_id= "<<std::this_thread::get_id()<<endl;
auto result = tmp.get();
cout <<"future_result= "<<result<<endl;
cout<<"My thread is over,thread_id= "<<std::this_thread::get_id()<<endl;
}
void example1()
{
std::chrono::system_clock::time_point start = std::chrono::system_clock::now();
future<int> result =std::async(std::launch::async,myThread);
cout<<"Continue.........................."<<endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
cout<<"result="<<result.get()<<endl;
auto end = std::chrono::system_clock::now();
auto t = std::chrono::duration_cast<std::chrono::seconds>(end - start).count();
cout<<"time= "<<t<<endl;
}
void example2()
{
std::promise<int> my_promise;
thread my_thread(myThread2,std::ref(my_promise),2);
my_thread.join();
future<int> my_future=my_promise.get_future();
thread my_thread2(myThread3,std::ref(my_future));
my_thread2.join();
}
int main(int argc, char *argv[])
{
cout<<"Main thread start,thread_id= "<<std::this_thread::get_id()<<endl;
example2();
cout<<"Main thread is over,thread_id= "<<std::this_thread::get_id()<<endl;
return 0;
}