C++ futures part 1: The mental model
Recorded: Oct. 21, 2026, 3:11 p.m.
| Original | Summarized |
C++ futures part 1: The mental model - The Old New Thing
Skip to main content Dev Blogs AI All .NET posts .NET MAUI C++ NuGet Microsoft for Developers Visual Studio All things Azure OData Windows Command Line
Dev BlogsThe Old New ThingC++ futures part 1: The mental model
October 12th, 2026 3 reactions C++ futures part 1: The mental model Raymond Chen Show more The C++ standard library has a group of related functions and classes: std::promise, std::packaged_task, std::async, std::future, and std::sharedfuture. Set a value. Here’s a simplified version that doesn’t support references. union { std::mutex m; The discriminant tells us what is in the union: Nothing (because nobody has set anything), a value, an exception, or nothing (because the value has been consumed). You can call the set methods only when the source is empty, so we’ll factor out the emptiness check. You can set a value or exception only once, so if there is already a value or exception, we yell at you. Otherwise, we save the value and notify anybody who was waiting for a value to be set. It’s basically the same as set_value except that we store an exception. void wait_for(duration dur) { You can either wait indefinitely or wait for a particular duration. 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. Regardless of how we intend to retrieve the value, it’s not legal to retrieve a value that has already been consumed. Also, if the result is an exception, we rethrow the exception. const T& get() { You can get the value, which returns a const reference to the underlying storage. Or you can consume the value, which moves the value out of the underlying storage and marks the value as consumed so nobody can consume or get it (because it’s not there any more). 3 6 0 Share on Facebook Share on X Share on Linkedin CategoryOld New ThingTopicsCode
6 comments Code of Conduct Sort by : Newest Newest
Nathan Phillip Brink (Binki) Copy link to comment by Nathan Phillip Brink (Binki) Collapse comment by Nathan Phillip Brink (Binki) Minor typo: I think “values an exceptions” should be “values and exceptions”. Log in to Vote or Reply
LB Copy link to comment by LB Collapse comment by LB Worth nothing, the standard library does not throw `future_already_retrieved` in practice. I thought it did, because why include it in the future error enum if not? But turns out, it’s just there because reasons. `std::future::get` throws `no_state` when the future is already retrieved. So, the “consumed” enumerator in your examples is effectively not used in practice: the source is destructed when the value is taken, or it is left alone for shared futures. Log in to Vote or Reply
Paul Herring Copy link to comment by Paul Herring Collapse comment by Paul Herring [...] I’m missing something here; what’s the value of what::empty? Log in to Vote or Reply
Richard Deeming Copy link to comment by Richard Deeming Collapse comment by Richard Deeming As a non-C++ dev, maybe I’m missing something, but it seems odd that the methods to read a value are protected by the same std::lock_guard g(m) as the methods to write a value. Log in to Vote or Reply
Yexuan Xiao Copy link to comment by Yexuan Xiao Collapse comment by Yexuan Xiao This is basically the idiomatic usage of C++ condition variables, a mechanism designed to handle spurious wakeups of the mutex while keeping exception safety. Also, as Pavel Vazharov said, Raymond used std::lock_guard incorrectly. Log in to Vote or Reply
Pavel Vazharov Copy link to comment by Pavel Vazharov Collapse comment by Pavel Vazharov I think that the answer for you doubts is in the behavior of std::condition_variable::wait. Log in to Vote or Reply Load more comments Read next October 13, 2026 Raymond Chen October 14, 2026 Raymond Chen
Stay informed Email * I would like to receive the The Old New Thing Newsletter. Privacy Statement. Subscribe
Are you sure you wish to delete this OK Sign in Theme Insert/edit link Close Enter the destination URL URL Link Text Open link in a new tab Or link to existing content Search No search term specified. Showing recent items. Search or use up and down arrow keys to select an item. Cancel
Code Block × Paste your code snippet Ok Surface Pro Account profile Microsoft in education Microsoft AI Azure Careers Your Privacy Choices Opt-Out Icon Your Privacy Choices Your Privacy Choices Opt-Out Icon Your Privacy Choices Consumer Health Privacy Sitemap |
The blog post by Raymond Chen, titled "C++ futures part 1: The mental model," introduces a conceptual framework for understanding the C++ standard library's futures and related components, namely std::promise, std::packaged_task, std::async, std::future, and std::sharedfuture. The article presents a simplified, illustrative "source" class that encapsulates the essential behaviors of these standard library abstractions, serving as a mental model for understanding their underlying mechanics. This source conceptually supports a set of fundamental operations: setting a value, setting an exception, waiting for a value or exception to be established, retrieving the value, and rethrowing any associated exception. The author provides a concrete implementation of this source class, which employs a discriminant—an enumeration—to track the internal state of the object. The possible states are "nothing" (no value or exception has been set), "value" (a value is present), "exception" (an exception is present), and "consumed" (the value has been retrieved). A union data structure is utilized to store either the value or the exception, while a mutex ensures exclusive, thread-safe access to the shared state, and a condition variable enables waiting for state transitions. The implementation details the set methods, such as set_value and set_exception, which first verify that the source is empty before storing a value or exception, then update the discriminant and notify any waiting threads. The wait and wait_for methods leverage the condition variable to block until the source is non-empty or until a specified duration has elapsed, effectively synchronizing producers and consumers. The consume method retrieves and moves the stored value, marking the source as consumed, while the get method returns a const reference to the value, also after waiting and ensuring the state is appropriate. The article emphasizes the critical role of the discriminant in managing the lifecycle of the source, ensuring that only one value or exception can be set and that retrieval is only permitted after waiting and after the state is correctly set. The thread safety is achieved through the combination of the mutex and condition variable, which together provide safe synchronization across multiple threads accessing the source concurrently. The accompanying comments and discussions on the blog post offer important clarifications and corrections to the implementation details. One reader points out that the correct synchronization pattern for condition variables requires using std::unique_lock in the wait and wait_for methods, as the condition variable's wait function atomically locks and unlocks the unique lock, and that using std::lock_guard in these contexts could lead to deadlock. Another commenter notes that in practice, std::future::get throws std::future_error::no_state when the future is already retrieved, rather than the future_already_retrieved error mentioned in the example code, indicating that the "consumed" state is effectively not enforced in the standard library's actual behavior for shared futures. Additional feedback highlights the necessity of handling spurious wakeups and maintaining exception safety, underscoring the careful design of the synchronization mechanisms. Raymond Chen notes that the actual standard library classes, such as std::promise, std::packaged_task, std::async, std::future, and std::sharedfuture, are built upon this source concept, and that the subsequent parts of the series will detail how these classes are constructed from the source. The author also mentions that writing this series is a personal effort to consolidate his understanding, as he frequently forgets the underlying principles. |