This explains a simple mental model for C++ futures and the related facilities (std::promise, std::packaged_task, std::async, std::future, std::shared_future) by reducing them to a single underlying "source" (the unnamed state in the standard). The source supplies four operations: set a value, set an exception, wait for a value/exception, and retrieve (or consume) the value. It is presented with a minimal implementation sketch that omits reference support and shows how higher-level objects can be built atop this core.
The implementation uses a discriminant enum (empty/nothing, value, exception, consumed) plus a union holding either T or std::exception_ptr, protected by a mutex and a condition_variable. set_value and set_exception lock, check emptiness, construct into the union, set the discriminant, and notify waiters. wait and wait_for block on the condition variable until nonempty. Retrieval checks for consumed/exception, rethrows exceptions, and either returns a const reference (get) or moves out the value and marks it consumed (consume). Notes point out set_value_at_thread_exit exists, destructor bookkeeping for the union is fiddly, and this is the first part of a series that will show how to compose the rest of the futures API.
Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.