r/cpp • • Mar 11 '26

std::promise and std::future

My googling is telling me that promise and future are heavy, used to doing an async task and communicating a single value, and are useful to get an exception back to the main thread.

I am asked AI and did more googling trying to figure out why I would use a less performant construct and what common use cases might be. It's just giving me ramblings about being easier to read while less performant. I don't really have an built in favoritism for performance vs readability and am experienced enough to look at my constraints for that.

However, I'd really like to have some good use-case examples to catalog promise-future in my head, so I can sound like a learned C++ engineer. What do you use them for rather than reaching for a thread+mutex+shared data, boost::asio, or coroutines?

38 Upvotes

20 comments sorted by

View all comments

Show parent comment

-1

u/smallstepforman Mar 12 '26

There is a background thread used to compute the future result, otherwise whats the point? A weak implementation may not spawn a thread and wait at the blocking pount, then execute a delayed function call that generates the result (but why bother with future if its not calculated in different thread).

Its just a wrapper for a thread and a signalling mechanism. Its not magic, just look at your std lib source code and all is revealed.

8

u/jwakely libstdc++ tamer, LWG chair Mar 12 '26

I wrote the std lib implementation for GCC.

I assure you, you're thinking of std::async.

std::future just holds a reference to a shared state, where the task can store the result. Actually creating a task to do that is not part of the future. It's done manually by separate code, or by std::async.