Tag Archives: future

Promises and futures

The words "promise" and "future" have historically been used rather interchangeably in concurrent programming, but they have very particular meanings in C++.

A promise is an asynchronous provider – it provides a result to a shared state
A future is an asynchronous return object – it reads a result from a shared state, waiting for it if necessary

  1. You construct a promise of type T, and you are creating a shared state that can store a variable of type T
  2. You can get a future from this promise with get_future()
  3. You can set the value of the promise’s variable with set_value()
  4. The future can read the value of the variable when it becomes available with its get() method

Below is a simple example of creating a promise, getting a future from it, sending the future to a thread, setting the value of the promise, and finally retrieving it from the future.

#include <iostream>
#include <functional>
#include <thread>
#include <future>

template <typename T>
void print (std::future<T>& fut) {
    T x = fut.get();
    std::cout << "value: " << x << "\n";

int main()
    std::promise<int> prom;
    std::future<int> fut = prom.get_future();
    std::thread thr (print<int>, std::ref(fut));