In ROS 2, when working with callbacks for subscriptions, timers, or services, you may want to choose between synchronous and asynchronous execution modes. This choice often depends on how you configure your callback groups and the executor. Here's a guide on how to set these modes in a ROS 2 C++ node:
Synchronous Mode
In synchronous mode, callbacks are processed one at a time in a single-threaded manner. This can be achieved by using the default executor without creating any special callback groups or using only the default callback group, which processes callbacks synchronously.
Here's a simple example:
#include <memory>
#include <rclcpp/rclcpp.hpp>
class SyncNode : public rclcpp::Node
{
public:
SyncNode()
: Node("sync_node")
{
subscription_ = this->create_subscription<std_msgs::msg::String>(
"topic",
10,
std::bind(&SyncNode::topic_callback, this, std::placeholders::_1)
);
}
private:
void topic_callback(const std_msgs::msg::String::SharedPtr msg)
{
RCLCPP_INFO(this->get_logger(), "Received: '%s'", msg->data.c_str());
}
rclcpp::Subscription<std_msgs::msg::String>::SharedPtr subscription_;
};
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared<SyncNode>());
rclcpp::shutdown();
return 0;
}
Asynchronous Mode
To achieve asynchronous behavior, you can use multiple threads to allow concurrent processing of callbacks. This is done by configuring an executor with a multi-threaded option or using callback groups explicitly.
Using Multi-threaded Executor
#include <rclcpp/rclcpp.hpp>
#include <std_msgs/msg/string.hpp>
class AsyncNode : public rclcpp::Node
{
public:
AsyncNode()
: Node("async_node")
{
subscription_ = this->create_subscription<std_msgs::msg::String>(
"topic",
10,
std::bind(&AsyncNode::topic_callback, this, std::placeholders::_1)
);
}
private:
void topic_callback(const std_msgs::msg::String::SharedPtr msg)
{
RCLCPP_INFO(this->get_logger(), "Received: '%s'", msg->data.c_str());
}
rclcpp::Subscription<std_msgs::msg::String>::SharedPtr subscription_;
};
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
// Use a Multi-threaded executor
rclcpp::executors::MultiThreadedExecutor executor;
auto async_node = std::make_shared<AsyncNode>();
executor.add_node(async_node);
executor.spin();
rclcpp::shutdown();
return 0;
}
Using Callback Groups
Callback groups allow finer control over which callbacks can be executed concurrently. You can create multiple callback groups and assign different executors to them as needed.
#include <rclcpp/rclcpp.hpp>
#include <std_msgs/msg/string.hpp>
class AsyncNodeWithCallbackGroup : public rclcpp::Node
{
public:
AsyncNodeWithCallbackGroup()
: Node("async_node_with_callback_group")
{
// Create a mutually exclusive callback group
auto callback_group = this->create_callback_group(
rclcpp::CallbackGroupType::MutuallyExclusive
);
// Assign the callback group to the subscription
auto subscription_options = rclcpp::SubscriptionOptions();
subscription_options.callback_group = callback_group;
subscription_ = this->create_subscription<std_msgs::msg::String>(
"topic",
10,
std::bind(&AsyncNodeWithCallbackGroup::topic_callback, this, std::placeholders::_1),
subscription_options
);
}
private:
void topic_callback(const std_msgs::msg::String::SharedPtr msg)
{
RCLCPP_INFO(this->get_logger(), "Received: '%s'", msg->data.c_str());
}
rclcpp::Subscription<std_msgs::msg::String>::SharedPtr subscription_;
};
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
rclcpp::executors::MultiThreadedExecutor executor;
auto async_node = std::make_shared<AsyncNodeWithCallbackGroup>();
executor.add_node(async_node);
executor.spin();
rclcpp::shutdown();
return 0;
}
In this setup, the MutuallyExclusive callback group will ensure that callbacks within that group do not run concurrently. You could switch to Reentrant if you want to allow concurrent execution of callbacks in that group. Adjusting the choice of callback group types and executor configurations allows you to set the appropriate sync or async operation mode for your needs.