future< T > 和 async 提供了一种接受线程返回值的方式
普通线程只能通过全局变量或者指针、引用来获取线程的返回值
其使用方式为:
future<T> result = async(para);//如果不使用引用,会在主线程里调用三次构造函数
result.get();
其中
- T 为返回参数类型
- para和构造普通线程的参数类似,不同的是,第一个参数可以选择launch::async、deferred或者不填,不填则默认为launch::async。
launch::async即默认情况下,在这条语句就创建线程并执行
如果使用launch::deferred,则会在调用result.get()的时候在主线程执行
result.get()或result.wait()类似于join()。主线程会卡在这等子线程执行完
下面是一个例子:
#include <iostream>
#include <string>
#include <future>
using namespace std;
class A
{
public:
A() { cout << "构造函数" << this_thread::get_id() << endl; };
A(const A &a) { cout << "复制构造函数" << this_thread::get_id() << endl; }
~A() {}
int mythread(int x)
{
cout << " 子线程 thread id = " << this_thread::get_id() << endl;
return x;
}
int operator()(int x)
{
cout << " 子线程 thread id = " << this_thread::get_id() << endl;
return x;
}
};
int fun(const A &pa) //这里如果不使用引用,还会再复制一份!!!
{
cout << " 子线程 thread id = " << this_thread::get_id() << endl;
return 5;
}
int main()
{
A a;
cout << " 主线程 thread id = " << this_thread::get_id() << endl;
//使用类的成员函数
//future<int> result = async(&A::mythread, &a, 5);
//使用普通函数(类对象的引用作函数参数)
//future<int> result = async(fun, ref(a) ); //这里如果不使用引用,会在主线程里调用三次构造函数
//使用仿函数
future<int> result = async(ref(a), 5);//如果不使用引用,会在主线程里调用三次构造函数
cout << "result = " << result.get() << endl;
system("pause");
return 0;
}