CodeTheRobot

C++ Intermediate · Lesson 11 of 27

Async programming: std::future and std::async

Running work in the background and collecting the result later.

Estimated time · 45–75 min

Learning goals

What you will understand

  • Explain async programming: std::future and std::async in your own words
  • Use it in a small robotics example
  • Verify the result instead of assuming it worked

Understand the idea first

The mental model

std::async runs a function, possibly on another thread, and returns a std::future. Calling get() on the future waits for the result and rethrows any exception the function threw. Use std::launch::async to force a real thread.

A future is the receiving end of a one-time result; std::promise is the sending end. Futures are good for one-off jobs such as loading a map, but for repeated events use callbacks or a queue. Do not call get() on the thread that must stay responsive.

Guided lesson

Work through these steps

  1. 1.

    Read the async programming: std::future and std::async example and identify what each line owns or changes.

  2. 2.

    Create a small source file, compile with -std=c++17 and warnings enabled, and run it.

  3. 3.

    Change one input, predict the result before running, then compare the output.

  4. 4.

    Record one compiler or runtime error and explain the correction in your own words.

Worked example

Read it before you run it

#include <future>
// Header for std::async, std::future and std::promise.
double slow_plan(double goal) { return goal * 2.0; }
// Stand-in for a slow planner.
auto pending = std::async(std::launch::async, slow_plan, 3.0);
// Start slow_plan(3.0) on another thread immediately.
std::cout << "planning...\n";
// This thread keeps working in the meantime.
double path = pending.get();
// Wait for the result (6.0); an exception would be rethrown here.
std::promise<int> p;
// The sending end of a one-time result.
std::future<int> f = p.get_future();
// The receiving end tied to the promise.
std::thread t{[&p] { p.set_value(42); }};
// Another thread fulfils the promise.
std::cout << f.get() << '\n';
// Blocks until the value arrives, then prints 42.
t.join();
// Always join the thread before it is destroyed.

What the example is doing

  1. 1.Read declarations from right to left: identify each value's type, name, and initial value.
  2. 2.Follow the data through each expression before considering syntax shortcuts.
  3. 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.

Watch it run · Messages between nodes

See what this code does

The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.

/topicpublishersubscribersubscribermessages delivered: 0MESSAGES BETWEEN NODES

Demo for Async programming: std::future and std::async. Expected result: 42

Practice code

Now type it yourself

Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice

#include <future>
#include <iostream>

int main() {
  // TODO: start a std::async job (std::launch::async) that returns 6 * 7, then get() the result
  std::cout << answer << '\n';
  return 0;
}

Expected output

42
Stuck? Show the full solution (try it yourself first)
#include <future>
#include <iostream>

int main() {
  auto pending = std::async(std::launch::async, [] { return 6 * 7; });
  int answer = pending.get();
  std::cout << answer << '\n';
  return 0;
}

Expected result

How you know it worked

  • After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
  • Changing the stated input produces the result you predicted.

Practical exercise

Apply the lesson

Start three std::async jobs that each sleep 100 ms and return a number. Measure that the total time is about 100 ms, not 300 ms. Make one job throw and show where the exception appears.

Before you continue

  • The program builds with -std=c++17 and no warnings
  • You can explain the key rule without reading the example
  • The normal and edge cases both have recorded results

If something goes wrong

The compiler reports that a name or type is unknown.

Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.

The program runs but the value is wrong.

Print the inputs and intermediate values, then check conversions, units, and collection order.