I have a camera_node publishing image to processer_node, images are published faster than they are processed.

When a new image appears in my image queue but the previous image is still processing, split a thread to bind a callback function to process the new image.

Is there any way to this?


1 Answer 1


Yes you can process multiple msgs coming on the same topic in multiple threads and you do not need to handle thread spinning, it can be done using callback group and executor functionalities of ros2. To achieve this you can follow these steps

rclcpp::executors::MultiThreadedExecutor executor;

  • Add your node to this executor


  • Now inside your node define a reentrant callback group (this allows parallel execution) and give this callback group in your topic subscription
    • my_callback_group = create_callback_group(rclcpp::CallbackGroupType::Reentrant);
    • rclcpp::SubscriptionOptions options;
    • options.callback_group = my_callback_group;
    • my_subscription = create_subscription<type>("/topic",rclcpp::SensorDataQoS(),callback, options);

This should work for your use case. For further understanding check out the executor concept on ros 2 wiki.

  • $\begingroup$ thanks for you answer, I have tried this, but do not work. I create a sub and a pub in a node. The callback of the sub just print a debug info and sleep 5s. And I use a for to publish msg for five times. The expected status is the sub_callback print five info without delay. However, the actual situation is that there is a five-second delay for every message I output $\endgroup$
    – Jalen
    Mar 20 at 13:27
  • $\begingroup$ I've seen a lot of articles about the multithreaded executor, but most of the descriptions of it are multithreaded execution of different callbacks within a node, are you sure he can multithread a single callback? $\endgroup$
    – Jalen
    Mar 20 at 13:29
  • $\begingroup$ Yes I am sure. Did you used Reentran callback group type or mutually exclusive? $\endgroup$
    – tomRob
    Mar 21 at 1:57
  • $\begingroup$ thanks, it is something wrong in my code, I fix it and it work well now. $\endgroup$
    – Jalen
    Mar 22 at 2:22
  • $\begingroup$ But when two or more callbacks operate the same variables within class in the same time, there is no error. Did ros2 solver this itself? How did ros2 does this, a simple lock or other things? $\endgroup$
    – Jalen
    Mar 22 at 2:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.