ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Simple example to make n nodes that all have 1 subscriber that subscribes to the topic "topic_name":

  #include <rclcpp/rclcpp.hpp>
  #include <std_msgs/msg/string.hpp>

  int main() {
  using namespace std_msgs::msg;
  rclcpp::init(0, nullptr);

  n = 100 // create this many nodes

  rclcpp::executors::SingleThreadedExecutor exec; // create executor
  std::vector<rclcpp::Node::SharedPtr> node_refs; // create vector to store node references
  std::vector<rclcpp::Subscription<String>::SharedPtr> sub_refs; // create vector to store sub references

  for (int i = 0; i < n; i++) { 
    auto node = std::make_shared<rclcpp::Node>("node_" + std::to_string(i)); // create a node
    auto sub = node->create_subscription<String>("topic_name", qos,
                                                   [](String::SharedPtr) {}); // add a sub to the node
    sub_refs.push_back(sub); // save a referene to the sub
    node_refs.push_back(node); // save  a reference to the node
    exec.add_node(node); // add the node with the sub to executor
  } 
  exec.spin(); // spin everything
  rclcpp::shutdown();
  return 0;
}

Simple example to make n nodes that all have 1 subscriber that subscribes to the topic "topic_name":

  #include <rclcpp/rclcpp.hpp>
  #include <std_msgs/msg/string.hpp>

  int main() {
  using namespace std_msgs::msg;
  rclcpp::init(0, nullptr);

  n = 100 100; // create this many nodes

  rclcpp::executors::SingleThreadedExecutor exec; // create executor
  std::vector<rclcpp::Node::SharedPtr> node_refs; // create vector to store node references
  std::vector<rclcpp::Subscription<String>::SharedPtr> sub_refs; // create vector to store sub references

  for (int i = 0; i < n; i++) { 
    auto node = std::make_shared<rclcpp::Node>("node_" + std::to_string(i)); // create a node
    auto sub = node->create_subscription<String>("topic_name", qos,
                                                   [](String::SharedPtr) {}); // add a sub to the node
    sub_refs.push_back(sub); // save a referene to the sub
    node_refs.push_back(node); // save  a reference to the node
    exec.add_node(node); // add the node with the sub to executor
  } 
  exec.spin(); // spin everything
  rclcpp::shutdown();
  return 0;
}