I’m confusing myself with difference between a future and a promise.
Obviously, they have different methods and stuff, but what is the actual use case?
Is it?:
- when I’m managing some async task, I use future to get the value “in future”
- when I’m the async task, I use promise as the return type to allow the user get a future from my promise
Future and Promise are the two separate sides of an asynchronous operation.
std::promiseis used by the “producer/writer” of the asynchronous operation.std::futureis used by the “consumer/reader” of the asynchronous operation.The reason it is separated into these two separate “interfaces” is to hide the “write/set” functionality from the “consumer/reader”.
One (incomplete) way to implement std::async using std::promise could be:
Using
std::packaged_taskwhich is a helper (i.e. it basically does what we were doing above) aroundstd::promiseyou could do the following which is more complete and possibly faster:Note that this is slightly different from
std::asyncwhere the returnedstd::futurewill when destructed actually block until the thread is finished.