packaged_task 是类模板,它的模板参数是各种可调用对象。packaged_task把可调用对象包装起来,作为线程入口函数。
#include<iostream>
#include<future>
using namespace std;
int myThread(int num)
{
cout << "Thread start id = " << this_thread::get_id() << endl;
chrono::milliseconds time(5000); //休息5秒
this_thread::sleep_for(time);
cout << "Thread end id = " << this_thread::get_id() << endl;
return num * 2;
}
int main()
{
cout << "Main start id = " << this_thread::get_id() << endl;
packaged_task<int(int)> package(myThread); //把函数myThread通过packaged_task包装起来。
thread thread(ref(package),5);
thread.join(); //等待线程执行完毕
future<int> result = package.get_future(); //future对象里保存线程的执行结果
cout << "result = " << result.get() << endl;
return 0;
}
执行结果:
packaged_task可是使用lambda表达式作为参数,而且packaged_task对象,也是一个可调用对象。
#include<iostream>
#include<future>
using namespace std;
int main()
{
cout << "Main start id = " << this_thread::get_id() << endl;
packaged_task<int(int)> package([](int num) {
cout << "Thread start id = " << this_thread::get_id() << endl;
chrono::milliseconds time(5000); //休息5秒
this_thread::sleep_for(time);
cout << "Thread end id = " << this_thread::get_id() << endl;
return num * 2;
});
package(5); //直接调用,并未创建新线程
future<int> result = package.get_future(); //future对象里保存线程的执行结果
cout << "result = " << result.get() << endl;
return 0;
}
执行结果:
注意,直接调用packaged_task对象时,并未创建新的线程,从运行结果可以看出,线程id始终为22296。