Raymond Chen: All of C++'s async machinery runs on one hidden class

C++ futures part 1: The mental model

Raymond Chen breaks down std::promise, std::packaged_task, std::async, std::future, and std::shared_future by revealing they all rest on a single unnamed shared state he calls the "source" — a struct with a mutex, a condition variable, and a union holding either a value or an exception. He sketches a simplified implementation showing how values and exceptions go in, how waiters block, and how results get consumed, then promises to build the rest on top next time.

I'm writing the series because I always forget how it works, but writing it down helps me remember.
  1. gsliepen

    > The wait_for method is why we have a condition variable at all. If it weren’t for that guy, we could have used std::atomic‘s wait and notify_all methods.

    No, the std::mutex is the reason you have a condition variable. Never mix std::atomic with std::mutex-and-friends, you are very likely introducing race conditions that way.

  2. ahartmetz

    This seems to omit the main point of it, though? That the compiler turns a function into a state machine that can restart from any of its suspension points. I guess that's the "state" variable, but what I'm talking about is what it contains and the partially compiler-generated code that deals with it.

    C++ async is unfortunately a "bring your own runtime" sort of model (for now), but it does handle the part that would be incredibly tedious by hand, building above mentioned state machine.

  3. thefourthchime

    Wow, I had no idea Raymond Chen was still doing blog posts. I used to love his posts back in the day.

More from this day

2026-10-21