CodeTheRobot

C++ Advanced · Lesson 04 of 23

Asynchronous patterns

Futures, worker threads and posting results back to the main loop safely.

Estimated time · 60–90 min

Learning goals

What you will understand

  • Explain asynchronous patterns 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

Asynchronous code starts work and continues without waiting. Common shapes are a future you check later, a worker thread that pushes results onto a queue, and a callback fired on completion. All of them must protect shared data and avoid blocking the event loop.

A robust pattern is: slow work runs on a worker, and its result is posted as an event to the main loop, which handles it on the loop thread. This keeps handlers single-threaded and easy to reason about, and is how ROS 2 action servers are structured.

Guided lesson

Work through these steps

  1. 1.

    Read the asynchronous patterns 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

std::mutex m;
// Guards the list of finished results.
std::vector<double> results;
// Results posted by the worker.
std::thread worker{[&] {
// Start slow work on another thread.
  std::this_thread::sleep_for(std::chrono::milliseconds(50));
// Pretend to plan a path for 50 ms.
  std::lock_guard<std::mutex> lock{m};
// Lock before touching the shared list.
  results.push_back(3.14);
// Post the result.
}};
// End of the worker; the lock is released here.
worker.join();
// Wait for the worker (a real program would poll or use a condition variable).
{
// A small scope so the lock is released as soon as we are done.
  std::lock_guard<std::mutex> lock{m};
// Lock while reading.
  for (double r : results) std::cout << r << '\n';
// Handle each result on the main thread.
}
// End of the scope; unlock.

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 Asynchronous patterns. Expected result: result 3.14

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 <chrono>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>

int main() {
  std::mutex m;
  std::vector<double> results;
  std::thread worker{[&] {
    std::this_thread::sleep_for(std::chrono::milliseconds(50));  // pretend to plan a path
    // TODO: lock m and push_back(3.14) onto results
  }};
  worker.join();
  std::lock_guard<std::mutex> lock{m};
  for (double r : results) std::cout << "result " << r << '\n';
  return 0;
}

Expected output

result 3.14
Stuck? Show the full solution (try it yourself first)
#include <chrono>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>

int main() {
  std::mutex m;
  std::vector<double> results;
  std::thread worker{[&] {
    std::this_thread::sleep_for(std::chrono::milliseconds(50));  // pretend to plan a path
    std::lock_guard<std::mutex> lock{m};
    results.push_back(3.14);
  }};
  worker.join();
  std::lock_guard<std::mutex> lock{m};
  for (double r : results) std::cout << "result " << r << '\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 worker threads that each post a result after a different delay. Handle the results on the main thread in the order they arrive, and confirm ThreadSanitizer reports no race.

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.