LmCast :: Stay tuned in

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
ASP.NET Core
Blazor
Entity Framework

C++
C#
F#
TypeScript

NuGet
Servicing
.NET Blog in Chinese

Microsoft for Developers
Agent Framework
Develop from the cloud
Xcode
ISE Developer
TypeScript
PowerShell
Python
Java
Java Blog in Chinese
Go
Microsoft Edge Dev
Microsoft 365 Developer
Microsoft Entra Identity Developer
Microsoft Entra PowerShell

Visual Studio
Visual Studio Code
Aspire

All things Azure
Azure SDK
Azure VM Runtime Team
Microsoft Azure
Azure Cosmos DB
Azure DocumentDB
Azure Data Studio
Azure SQL
DevOps
DirectX
Microsoft Foundry
Power Platform

OData
Unified Data Model (IDEAs)

Windows Command Line
#ifdef Windows
Inside MSIX
MIDI and music
React Native
The Old New Thing
Foundry on Windows Windows Developer

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.
The idea is that all of these classes are built of a single unnamed class which the C++ standard library calls the “state”, but for the purpose of discussion, I’m going to call it the source, since it is the thing that produces the value, and it behaves analogously to a C# task completion source.
The source conceptually supports these operations:

Set a value.
Set an exception.
Wait for a value or exception to be set.
Retrieve the value or rethrow the exception.

Here’s a simplified version that doesn’t support references.
template<typename T>
struct source
{
private:
enum what {
nothing,
value,
exception,
consumed,
} d; // discriminant

union {
T value;
std::exception_ptr ex;
} r; // result

std::mutex m;
std::condition_variable cv;

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).
The mutex ensures thread-safe access to the other members, and the condition variable lets us wait for somebody to set a value or exception.
void must_be_empty() {
if (d != what::empty) {
throw std::future_error(future_errc::promise_already_satisfied);
}
}

You can call the set methods only when the source is empty, so we’ll factor out the emptiness check.
public:
void set_value(T& v) {
std::lock_guard g(m);
must_be_empty();
new(&r.value) T(v); // "r.value = v"
d = what::value;
cv.notify_all();
}

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.
I won’t bother with the overload that takes T&&; it’s the same thing, but with a std::move().
There is also a set_value_at_thread_exit which will be another topic for another day.
Instead of setting a value, you can set an exception:
void set_exception(std::exception_ptr ex) {
std::lock_guard g(m);
must_be_empty();
new(&r.ex) std::exception_ptr(ex); // "r.ex = ex"
d = what::exception;
cv.notify_all();
}

It’s basically the same as set_value except that we store an exception.
That’s how values an exceptions go into the source. The next part is waiting for the source to become nonempty.
void wait() {
std::lock_guard g(m);
while (d == what::empty) {
cv.wait(g);
}
}

void wait_for(duration dur) {
std::lock_guard g(m);
cv.wait_for(g, dur, [&] { return d != what::empty; });
}

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.
The last part is getting the values out.
void can_get() {
if (d == what::consumed) {
throw std::future_error(future_errc::future_already_retrieved);
}
if (d == what::exception) {
std::rethrow_exception(r.ex);
}
}

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.
T consume() {
wait();
std::lock_guard g(m);
can_get();
d = what::consumed;
return std::move(r.v);
}

const T& get() {
wait();
std::lock_guard g(m);
can_get();
return r.v;
}
};

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).
We can now build our other objects and functions out of this guy. We’ll do that next time.
Bonus chatter: Writing the destructor is left as an exercise for the reader. It’s not hard, but it’s annoying because of the union.
Bonus bonus chatter: I’m writing the series because I always forget how it works, but writing it down helps me remember.

3

6

0

Share on Facebook

Share on X

Share on Linkedin

CategoryOld New ThingTopicsCode
Share


Author
Raymond ChenRaymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

6 comments
Join the discussion.
Leave a commentCancel replySign in

Code of Conduct

Sort by :

Newest

Newest
Popular
Oldest

Nathan Phillip Brink (Binki)


5 days ago
0

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


6 days ago · Edited
0

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


1 week ago
1

Copy link to comment by Paul Herring

Collapse comment by Paul Herring


enum what {
nothing,
value,
exception,
consumed,
} d; // discriminant

[...]
void must_be_empty() {
if (d != what::empty) {

I’m missing something here; what’s the value of what::empty?

Log in to Vote or Reply

Richard Deeming


1 week ago
1

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.
In C# at least, something like that would lead to a deadlock: the reading thread is blocked waiting for the value to be set, and the writing thread is blocked waiting for the reading thread to release the mutex.
But as I said, maybe I’m missing something?

Log in to Vote or Reply

Yexuan Xiao


1 week ago
1

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


1 week ago
2

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.
It takes a reference to std::unique_lock and atomically calls lock.unlock() and blocks waiting. (I think the article has a mistake in the wait member functions where it uses std::lock_guard. It should be std::unique_lock.

Log in to Vote or Reply

Load more comments

Read next

October 13, 2026
C++ futures part 2: The mental model for std::promise, std::packaged_task

Raymond Chen

October 14, 2026
C++ futures part 3: The mental model for std::async

Raymond Chen

Stay informed
Get notified when new posts are published.

Email *

Country/Region *
Select...United StatesAfghanistanÅland IslandsAlbaniaAlgeriaAmerican SamoaAndorraAngolaAnguillaAntarcticaAntigua and BarbudaArgentinaArmeniaArubaAustraliaAustriaAzerbaijanBahamasBahrainBangladeshBarbadosBelarusBelgiumBelizeBeninBermudaBhutanBoliviaBonaireBosnia and HerzegovinaBotswanaBouvet IslandBrazilBritish Indian Ocean TerritoryBritish Virgin IslandsBruneiBulgariaBurkina FasoBurundiCabo VerdeCambodiaCameroonCanadaCayman IslandsCentral African RepublicChadChileChinaChristmas IslandCocos (Keeling) IslandsColombiaComorosCongoCongo (DRC)Cook IslandsCosta RicaCôte dIvoireCroatiaCuraçaoCyprusCzechiaDenmarkDjiboutiDominicaDominican RepublicEcuadorEgyptEl SalvadorEquatorial GuineaEritreaEstoniaEswatiniEthiopiaFalkland IslandsFaroe IslandsFijiFinlandFranceFrench GuianaFrench PolynesiaFrench Southern TerritoriesGabonGambiaGeorgiaGermanyGhanaGibraltarGreeceGreenlandGrenadaGuadeloupeGuamGuatemalaGuernseyGuineaGuinea-BissauGuyanaHaitiHeard Island and McDonald IslandsHondurasHong Kong SARHungaryIcelandIndiaIndonesiaIraqIrelandIsle of ManIsraelItalyJamaicaJan MayenJapanJerseyJordanKazakhstanKenyaKiribatiKoreaKosovoKuwaitKyrgyzstanLaosLatviaLebanonLesothoLiberiaLibyaLiechtensteinLithuaniaLuxembourgMacau SARMadagascarMalawiMalaysiaMaldivesMaliMaltaMarshall IslandsMartiniqueMauritaniaMauritiusMayotteMexicoMicronesiaMoldovaMonacoMongoliaMontenegroMontserratMoroccoMozambiqueMyanmarNamibiaNauruNepalNetherlandsNew CaledoniaNew ZealandNicaraguaNigerNigeriaNiueNorfolk IslandNorth MacedoniaNorthern Mariana IslandsNorwayOmanPakistanPalauPalestinian AuthorityPanamaPapua New GuineaParaguayPeruPhilippinesPitcairn IslandsPolandPortugalPuerto RicoQatarRéunionRomaniaRwandaSabaSaint BarthélemySaint Kitts and NevisSaint LuciaSaint MartinSaint Pierre and MiquelonSaint Vincent and the GrenadinesSamoaSan MarinoSão Tomé and PríncipeSaudi ArabiaSenegalSerbiaSeychellesSierra LeoneSingaporeSint EustatiusSint MaartenSlovakiaSloveniaSolomon IslandsSomaliaSouth AfricaSouth Georgia and South Sandwich IslandsSouth SudanSpainSri LankaSt HelenaAscensionTristan da CunhaSurinameSvalbardSwedenSwitzerlandTaiwanTajikistanTanzaniaThailandTimor-LesteTogoTokelauTongaTrinidad and TobagoTunisiaTurkeyTurkmenistanTurks and Caicos IslandsTuvaluU.S. Outlying IslandsU.S. Virgin IslandsUgandaUkraineUnited Arab EmiratesUnited KingdomUruguayUzbekistanVanuatuVatican CityVenezuelaVietnamWallis and FutunaYemenZambiaZimbabwe

I would like to receive the The Old New Thing Newsletter. Privacy Statement.

Subscribe


Follow this blog

Are you sure you wish to delete this
comment?

OK
Cancel

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
Cancel

Surface Pro
Surface Laptop
Surface Laptop Ultra
Surface RTX Spark Dev Box
Copilot for organizations
Copilot for personal use
Explore Microsoft products
Windows 11 apps

Account profile
Download Center
Microsoft Store support
Returns
Order tracking
Certified Refurbished
Microsoft Store Promise
Flexible Payments

Microsoft in education
Devices for education
Microsoft Teams for Education
Microsoft 365 Education
How to buy for your school
Educator training and development
Deals for students and parents
AI for education

Microsoft AI
Microsoft Security
Dynamics 365
Microsoft 365
Microsoft Power Platform
Microsoft Teams
Microsoft 365 Copilot
Small Business

Azure
Microsoft Developer
Microsoft Learn
Support for AI marketplace apps
Microsoft Tech Community
Microsoft Marketplace
Software companies
Visual Studio

Careers
About Microsoft
Company news
Privacy at Microsoft
Investors
Diversity and inclusion
Accessibility
Sustainability

Your Privacy Choices Opt-Out Icon

Your Privacy Choices

Your Privacy Choices Opt-Out Icon

Your Privacy Choices

Consumer Health Privacy

Sitemap
Contact Microsoft
Privacy
Manage cookies
Terms of use
Trademarks
Safety & eco
Recycling
About our ads

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.