multithreading · advanced
std::future, promise & async
How std::future/promise (and std::async) pass a result across threads: get() blocks until ready, then returns the value or rethrows.
🔑 Key line
A future/promise is a one-shot channel: get() blocks until set_value (or the async result); set synchronizes-with get; exceptions rethrow at get().
The code
std::promise<int> p;std::future<int> f = p.get_future();
std::thread worker([&] { p.set_value(42); }); // produceint r = f.get(); // blocks until ready -> 42worker.join();
// one-shot: launch + future togetherstd::future<int> g = std::async(compute);int s = g.get(); // result, or rethrows the task's exceptionWhat this lesson walks through
- 01promise and future share one state
- 02f.get() blocks until ready
- 03Worker calls set_value(42)
- 04get() unblocks and returns 42
- 05std::async = task + future in one
- 06Exceptions travel through the future
- 07The model
std::promise is the write end; the std::future it hands out is the read end. They share a single state object, initially empty.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of std::future, promise & async and 100+ animated C++ interview lessons.