I am trying to establish some heuristics to help me decide the appropriate std::thread
class to use.
As I understand it, from highest level (simplest to
When you have two levels of async, you need to use a promise. Eg:
void fun()
{
std::promise<int> p;
std::future<int> f = p.get_future();
std::future<void> f2;
auto f3 = std::async([&]{
// Do some other computation
f2 = std::async([&]{ p.set_value(42);});
// Do some other work
});
// Do some other work
// Now wait for the result of async work;
std::cout << f.get();
// Do some other work again
// Wait for async threads to complete
f3.wait();
f2.wait();
}
You don't choose to use a promise
instead of the others, you use a promise
to fulfill a future
in conjunction with the others. The code sample at cppreference.com gives an example of using all four:
#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(std::move(task)).detach(); // 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( [](std::promise<int>& p){ p.set_value(9); },
std::ref(p) ).detach();
std::cout << "Waiting...";
f1.wait();
f2.wait();
f3.wait();
std::cout << "Done!\nResults are: "
<< f1.get() << ' ' << f2.get() << ' ' << f3.get() << '\n';
}
prints
Waiting...Done!
Results are: 7 8 9
Futures are used with all three threads to get their results, and a promise
is used with the third one to fulfill a future
by means other than a return value. Also, a single thread can fulfill multiple future
s with different values via promise
s, which it can't do otherwise.
An easy way to think of it is that you can either set a future
by returning a value or by using a promise
. future
has no set
method; that functionality is provided by promise
. You choose what you need based on what the situation allows.