Trying to work with packaged_task<T>
std::async
creates a thread executed asynchronously and process data which we can access into, using the class template std::future<T>
and the get()
method.
What should i know about how packaged_task<T>
works, in difference with std::async
?
And was the thread related to packaged_task<T>
, created when we invoked the task(x)
function ?
Taking the code example :
#include <iostream>
#include <thread>
#include <future>
#include <chrono>
using namespace std::chrono;
int main()
{
int x(0),xr(0);
std::future<int> fdata = std::async(std::launch::async,[&](int data) mutable throw() ->
int
{data++;
std::this_thread::sleep_for(seconds(2));
return data;}
,x);
std::packaged_task<int(int)> task([&](int data) mutable throw() ->
int
{data++;
std::this_thread::sleep_for(seconds(2));
return data;}
);
std::future<int> xrp = task.get_future();
task(x);
xr=fdata.get();
std::cout<<xr<<std::endl;
std::cout<<xrp.get()<<std::endl;
return 0;
}