C++ futures part 1: The mental model

Raymond Chen

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.