Defination of packaged_task :
The class template packaged_task wraps any Callable target, which can be invoked later. The callable objects can be function, lambda expression, bind expression, or another function object.
Both std::packaged_task and std::async to used create asynchronous tasks. One of the main differences between the two is std::packaged_task waits for the asynchronous result to return, and std::async will not wait.
Note :
- The std::packaged_task is introduced in C++ 11.
- The std::packed_task can be invoked asynchronously.
- Future objects are used to get return values and exceptions via the shared state.
Example:
#include "stdafx.h"
#include <iostream>
#include <thread>
#include <future>
#include <chrono>
using namespace std;
double work(int value)
{
cout<<"Execution started"<<endl;
this_thread::sleep_for(chrono::milliseconds(5000));
cout<<"Function work1 executed"<<endl;
return value + 3.14;
}
int _tmain(int argc, _TCHAR* argv[])
{
try
{
packaged_task< double(int) > task(work);
future<double> objFuture = task.get_future();
//task(10);
thread t(move(task), 10);
cout<<"Result : "<< objFuture.get()<<endl;
}
catch(exception &e)
{
cerr<<e.what()<<endl;
}
return 0;
}