c++multithreadingasynchronousdifferencepackaged-task

Is std::packaged_task<T> (Function Template) an std::async (FT) with an invoked function?


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;
}

Solution

  • std::async(ploicy, callable, args...)
    

    launches a new thread (if the resources are available) if the policy is std::async::launch.

    If the policy is not determined, it may launch or not.

    If the policy is std::async::deferred, won't launch.

    while std::packaged_task wraps your callable so that it can be invoked asynchronously using a new thread like

    auto t1 = std::thread(std::move(taskObj), args...);
    ....
    t1.join();
    

    But If you used it as you do in your example, it wouldn't launch a new thread. It doesn't launch a new thread by itself but it can be used to do that.