packaged_task将一个函数(lambda函数,函数对象等)封装在异步执行的线程中,并可通过futrue在另一个线程中获得函数的运行结果:
#include <iostream>
#include <thread>
#include <future>
using namespace std;
int add(int a, int b)
{
return (a+b);
}
using F = int (int, int);
int main ()
{
packaged_task<F> task(add); //构造时传递用于异步执行的函数指针add
future<int> future = task.get_future(); //future模板参数类型为函数add的返回值类型
thread t1(move(task), 1, 2); //创建线程,同时传递函数add的运行参数
int res = future.get(); //获得函数add在另一个线程中的运行结果
t1.join();
cout<<"add(1,2)="<<res<<endl; //输出:add(1,2)=3
return 0;
}