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

How to handle a blocking function inside a node?

asked 2023-03-21 03:37:50 -0600

Voklaif gravatar image


I am trying to create a node (I am using ROS2 Foxy with Python) that will have a two way communication with RabbitMQ.

My problem is that in order for me to listen to a RabbitMQ queue I have to use a blocking function that stops the rest of my node to keep functioning (for example - the node should also send messages to the RabbitMQ).

To solve this issue, I have considered two options:

  1. Create two separate nodes, first node to listen to the RabbitMQ queue and the other node for sending messages. This approach seems more straightforward and compatible with the ROS2 framework, but may require more resources with the extra node. (I might be wrong on that one).
  2. Use threading in my node - I will run a separate thread inside my node to listen to the RabbitMQ queue.

I would appreciate any advice you could provide. Thanks!

edit retag flag offensive close merge delete

4 Answers

Sort by ยป oldest newest most voted

answered 2023-03-26 02:27:45 -0600

Voklaif gravatar image

Thank you for your replies.

I've actually used regular threading (had to progress somehow before seeing the answers here) and it works quite well. Once I'll have time to go back to redo it, I'll defiantly try the rclpy threading.

edit flag offensive delete link more

answered 2023-03-22 19:06:57 -0600

ljaniec gravatar image

You can check this nice repository for the second option with threading with rclpy:


Some toy examples to demonstrate threading in rclpy.

tl;dr: To achieve parallel tasks using rclpy you must use BOTH a MultiThreadedExecutor AND custom Callback Groups!!

edit flag offensive delete link more

answered 2023-03-22 18:20:13 -0600

feltarock gravatar image

Yeah both options are valid, and if you go down the threading option, you might avoid writing some of the thread creation logic by using a MultiThreadedExecutor.

Personally I think I might vote for option 1 in this case if you aren't insanely resource constrained. I've been finding small, single-threaded, single-purpose nodes to be easier to debug and reason about and it avoids you needing to consider any multi-threaded locking mechanisms in your code (which are easy to get wrong). If you're already running Python on your target system you probably don't need to worry too much about the small overhead of an extra ROS node vs combining into a single node.

edit flag offensive delete link more

answered 2023-03-22 09:51:28 -0600

GuimingChen gravatar image

You can probably use rclpy.executors.MultiThreadedExecutor() to achieve what you want.

This example shows you how to implement it in ROS 2 foxy.

edit flag offensive delete link more

Question Tools

1 follower


Asked: 2023-03-21 03:37:50 -0600

Seen: 445 times

Last updated: Mar 26 '23