C++11多线程(四)future<T> 和 async

future< T > 和 async 提供了一种接受线程返回值的方式
普通线程只能通过全局变量或者指针、引用来获取线程的返回值
其使用方式为:

future<T> result = async(para);//如果不使用引用,会在主线程里调用三次构造函数
result.get();

其中

  1. T 为返回参数类型
  2. 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值