CodeBlanks Logo Icon CodeBlanks

std::future

Learn value passing with std::future and promise.

std::future

std::future<T> holds a T result that is not computed yet. It is created by std::async or std::promise. f.get() blocks until the result is ready and returns the value.

get can be called only once; a second call throws std::future_error. valid() checks whether the future still holds a result. wait() blocks without fetching; wait_for and wait_until accept a timeout. A future is ideal for single-consumer synchronization.

promise and future relationship

std::promise<T> is the side that sets the result; std::future<T> is the side that reads it. A future is taken from a promise with p.get_future(); a value is written with p.set_value(v). This is the low-level way to pass a value to another thread.

std::async wires this relationship automatically; the user does not handle promise and future directly. But when custom synchronization is needed the pair is used manually. This is the foundation of the producer-consumer pattern. Each promise is paired with one future; the relation is one-to-one.

Practice Fetch a result with future

Write int compute() with body return 100;. In main write std::future<int> f = std::async(std::launch::async, compute);, then fetch the result with int result = f.get(); and print std::cout << result;.

Starter code

main.cpp
#include <iostream>
#include <future>

// Write the compute function

int main() {
    // Launch a future, fetch the result, print
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <future>

int compute() {
    return 100;
}

int main() {
    std::future<int> f = std::async(std::launch::async, compute);
    int result = f.get();
    std::cout << result;
    return 0;
}

Expected output

100

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the get line

Question
std::future<int> f = std::async(std::launch::async, compute);
int r = ____;
Answer
std::future<int> f = std::async(std::launch::async, compute);
int r = f.get();

Explanation: f.get() waits and returns the result.

2 What does future::get() do?

  • Deletes the result
  • Only waits
  • Waits for the result and returns it Correct answer
  • Starts the thread

Explanation: get() blocks until the result is ready and returns the value.

3 Match each expression to its role

Term Meaning
f.get() Fetch the result
f.wait() Only wait
f.valid() Is valid?
p.set_value(v) Write the value

All lessons in Advanced