I’m fairly familiar with C++11’s std::thread, std::async and std::future components (e.g. see this answer), which are straight-forward.
However, I cannot quite grasp what std::promise is, what it does and in which situations it is best used. The standard document itself doesn’t contain a whole lot of information beyond its class synopsis, and neither does std::thread.
Could someone please give a brief, succinct example of a situation where an std::promise is needed and where it is the most idiomatic solution?
In the words of [futures.state] a
std::futureis an asynchronous return object (“an object that reads results from a shared state”) and astd::promiseis an asynchronous provider (“an object that provides a result to a shared state”) i.e. a promise is the thing that you set a result on, so that you can get it from the associated future.The asynchronous provider is what initially creates the shared state that a future refers to.
std::promiseis one type of asynchronous provider,std::packaged_taskis another, and the internal detail ofstd::asyncis another. Each of those can create a shared state and give you astd::futurethat shares that state, and can make the state ready.std::asyncis a higher-level convenience utility that gives you an asynchronous result object and internally takes care of creating the asynchronous provider and making the shared state ready when the task completes. You could emulate it with astd::packaged_task(orstd::bindand astd::promise) and astd::threadbut it’s safer and easier to usestd::async.std::promiseis a bit lower-level, for when you want to pass an asynchronous result to the future, but the code that makes the result ready cannot be wrapped up in a single function suitable for passing tostd::async. For example, you might have an array of severalpromises and associatedfutures and have a single thread which does several calculations and sets a result on each promise.asyncwould only allow you to return a single result, to return several you would need to callasyncseveral times, which might waste resources.