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

Revision history [back]

In one case I had a couple of nodes, one which needed a single thread and the other which doesn't care about thread affinity but blocks for a long time (it needs to do something other than select() and block).

Below I spin the one node in a regular std::thread and the other runs separate for that (maybe for symmetry it ought to be in another std thread also...):

void run_usb_cam(FooType foo)
{
  rclcpp::executors::SingleThreadedExecutor executor;
  auto usb_cam = std::make_shared<usb_cam::UsbCam>(foo);
  executor.add_node(usb_cam);
  executor.spin();
}
...

  rclcpp::executors::SingleThreadedExecutor single_executor;
  // imgui_ros has to be single threaded for now to avoid context switches with opengl
  auto imgui_ros = std::make_shared<imgui_ros::ImguiRos>(foo);
  single_executor.add_node(imgui_ros);

  std::thread cam_thread(std::bind(run_usb_cam, foo));
  single_executor.spin();
  cam_thread.join();

https://github.com/lucasw/imgui_ros/blob/crystal/imgui_ros/src/nodes/usb_cam_viewer.cpp

In one case I had a couple of nodes, one which needed a single thread and the other which doesn't care about thread affinity but blocks for a long time (it needs to do something other than select() and block).

Below I spin the one node in a regular std::thread and the other runs separate for that (maybe for symmetry it ought to be in another std thread also...):

void run_usb_cam(FooType foo)
{
  rclcpp::executors::SingleThreadedExecutor executor;
  auto usb_cam = std::make_shared<usb_cam::UsbCam>(foo);
  executor.add_node(usb_cam);
  executor.spin();
}
...

  rclcpp::executors::SingleThreadedExecutor single_executor;
  // imgui_ros has to be single threaded for now to avoid context switches with opengl
  auto imgui_ros = std::make_shared<imgui_ros::ImguiRos>(foo);
  single_executor.add_node(imgui_ros);

  std::thread cam_thread(std::bind(run_usb_cam, foo));
  single_executor.spin();
  cam_thread.join();

https://github.com/lucasw/imgui_ros/blob/crystal/imgui_ros/src/nodes/usb_cam_viewer.cpp

I initially tried a while loop with spin_some on both executors, but even if one of the executors is multi threaded spin_some doesn't return until all the jobs it was running (however concurrently) are complete, so it blocks the other executor.