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); }); // produce
int r = f.get(); // blocks until ready -> 42
worker.join();
// one-shot: launch + future together
std::future<int> g = std::async(compute);
int s = g.get(); // result, or rethrows the task's exception

What this lesson walks through

  1. 01promise and future share one state
  2. 02f.get() blocks until ready
  3. 03Worker calls set_value(42)
  4. 04get() unblocks and returns 42
  5. 05std::async = task + future in one
  6. 06Exceptions travel through the future
  7. 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.

← Previous
False Sharing & Cache Lines
Next →
Process vs Thread