CodeTheRobot

C++ Advanced · Lesson 22 of 23

Multi-threaded executors and callback groups

SingleThreadedExecutor vs MultiThreadedExecutor and avoiding blocked callbacks.

Estimated time · 90–120 min

Learning goals

What you will understand

  • Explain multi-threaded executors and callback groups 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

An executor takes ready callbacks (messages, timers, service requests) and runs them. rclcpp::spin uses a single-threaded executor: callbacks run one at a time. A MultiThreadedExecutor uses a pool of threads so callbacks can run in parallel, but only callbacks in different callback groups, or in a Reentrant group, may overlap.

A MutuallyExclusive group (the default) never runs two of its callbacks together, so it is safe but serial. Use several groups when one callback blocks, such as a service client waiting for a response, and protect shared data with a mutex. Measure before adding threads.

Guided lesson

Work through these steps

  1. 1.

    Read the multi-threaded executors and callback groups 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

auto node = std::make_shared<ArmNode>();
// Create the node.
rclcpp::executors::MultiThreadedExecutor exec{rclcpp::ExecutorOptions(), 4};
// An executor with a pool of four threads.
exec.add_node(node);
// Let the executor run the node's callbacks.
exec.spin();
// Run until shutdown; callbacks may now run in parallel.
auto fast = create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive);
// Group for callbacks that must not overlap each other.
auto slow = create_callback_group(rclcpp::CallbackGroupType::Reentrant);
// Group whose callbacks may run in parallel.
rclcpp::SubscriptionOptions opts; opts.callback_group = fast;
// Choose the group for a subscription.
sub_ = create_subscription<std_msgs::msg::String>("chatter", 10, cb, opts);
// The subscription's callback now belongs to the fast group.

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 Multi-threaded executors and callback groups. Expected result: The 10 ms timer keeps running while the slow callback sleeps

Practice code

Now type it yourself

Copy the starter into your ROS 2 package, replace every TODO, then build with colcon build and run it from a sourced terminal.

// main() of a node that has a slow timer and a fast timer in different callback groups
#include "rclcpp/rclcpp.hpp"

int main(int argc, char** argv) {
  rclcpp::init(argc, argv);
  auto node = std::make_shared<ArmNode>();
  // TODO: use a MultiThreadedExecutor with 4 threads, add the node, and spin
  rclcpp::shutdown();
  return 0;
}

Expected output

The 10 ms timer keeps running while the slow callback sleeps
Stuck? Show the full solution (try it yourself first)
// main() of a node that has a slow timer and a fast timer in different callback groups
#include "rclcpp/rclcpp.hpp"

int main(int argc, char** argv) {
  rclcpp::init(argc, argv);
  auto node = std::make_shared<ArmNode>();
  rclcpp::executors::MultiThreadedExecutor exec{rclcpp::ExecutorOptions(), 4};
  exec.add_node(node);
  exec.spin();
  rclcpp::shutdown();
  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

Write a node with a timer whose callback sleeps 500 ms and a second 10 ms timer. Run them with a single-threaded executor and note the delay, then put them in different callback groups on a MultiThreadedExecutor and measure again.

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.