1.使用async来处理:
第一步:使用async启动一个异步任务创建线程,返回类型为一个future对象
第二步:使用对应future的对象接收async的返回值,之后通过get函数获取future里面的内容
async有两种线程处理方法:
1.使用launch::asnyc方式:则创建线程,并执行线程处理函数。
#include<iostream>
#include<thread>
#include<future>
using namespace std;
int text1(int a)
{
cout << "id:" << this_thread::get_id()<<" start" << endl;
cout << "id:" << this_thread::get_id() << " end" << endl;
return a + 100;
}
int main()
{
future<int> f=async(launch::async,text1, 10);
cout << "主线程" << endl;
cout << f.get() << endl;
return 0;
}
运行效果如下:
2.使用launch::deferred方式:线程处理函数延迟,直到遇到wait和get方法时,才会执行,本质是没有创建线程的。
#include<iostream>
#include<thread>
#include<future>
using namespace std;
int text1(int a)
{
cout << "id:" << this_thread::get_id()<<" start" << endl;
cout << "id:" << this_thread::get_id() << " end" << endl;
return a + 100;
}
int main()
{
future<int> f=async(launch::deferred,text1, 10);
cout << "主线程" << endl;
//cout << f.get() << endl;或者是f.wait()也可以创建线程
return 0;
}
运行效果如下:
如果把cout << f.get() << endl;的注释删掉,则运行效果如下:
2.使用thread来处理:
第一步:通过类模板package_task来包装线程处理函数
第二步:通过package_task对象调用get_future方法,获得future对象,之后再调用get方法即可。
#include<iostream> #include<thread> #include<future> using namespace std; int text1(int a) { cout << "id:" << this_thread::get_id()<<" start" << endl; cout << "id:" << this_thread::get_id() << " end" << endl; return a + 100; } void test1()//打包普通函数 { //这里的模板类型是返回值为int,参数为一个int的函数类型,注意这里的函数类型要和你要作为线程处理函数的类型一致 packaged_task<int(int)> t(text1); //注意,这里的thread的构造函数的参数是packaged_task类的引用,所以需要使用ref转换为右值引用,接着传入参数 thread t1(ref(t), 10); t1.join(); cout << t.get_future().get() << endl; } class person { public: int print(int a) { cout << "id:" << this_thread::get_id() << " start" << endl; cout << "id:" << this_thread::get_id() << " end" << endl; return a + 10; } }; void test2()//打包类的成员函数 { person p;//创建对象 //这里要通过函数适配器bind来绑定类的成员函数,第一个参数是类的成员函数,第二个参数是指定类的对象,第三个参数是根据成员函数的参数的个数,来设置占位符 packaged_task<int(int)> tt(bind(&person::print,&p,placeholders::_1)); thread t2(ref(tt),10);//同样转为右值引用后传入参数 t2.join(); cout<<tt.get_future().get() << endl; } int main() { test2(); return 0; }
test1普通函数运行效果如下:
test2类的成员函数运行效果如下: