1

I'm learning about C++ thread library, and I feel the async, packaged_task and promise are doing things that are pretty similar: they all run a function asynchronously in a separate thread, and return a future object that stores the function's return value. So I do not quite understand why we need all three of them, instead of always using async.

Below is an example code from std::future documentation:

#include <iostream>
#include <future>
#include <thread>

int main()
{
    // future from a packaged_task
    std::packaged_task<int()> task([]{ return 7; }); // wrap the function
    std::future<int> f1 = task.get_future();  // get a future
    std::thread t(std::move(task)); // launch on a thread

    // future from an async()
    std::future<int> f2 = std::async(std::launch::async, []{ return 8; });

    // future from a promise
    std::promise<int> p;
    std::future<int> f3 = p.get_future();
    std::thread( [&p]{ p.set_value_at_thread_exit(9); }).detach();

    std::cout << "Waiting..." << std::flush;
    f1.wait();
    f2.wait();
    f3.wait();
    std::cout << "Done!\nResults are: "
          << f1.get() << ' ' << f2.get() << ' ' << f3.get() << '\n';
    t.join();
}  

and this example at least shows under certain circumstances, std::async can replace the other two. Can someone give an example that I have to use promise or packaged_task where the std::async is not enough to do the job?

DiveIntoML
  • 2,347
  • 2
  • 20
  • 36
  • 1
    Note: `packaged_task` is thread-agnostic. It's just a wrapper for a function that returns a result, and a `future` that can await and accesses the result. It doesn't automatically call the function. The client has to explicitly do that by invoking the task's `operator()`, and whatever thread invokes `operator()`, that's the thread that the function runs in. – Solomon Slow Mar 20 '19 at 19:22

0 Answers0