Ask Your Question

Is It Safe to Subscribe Multiple Times to the Same Topic?

asked 2018-04-20 12:09:35 -0500

afsantos gravatar image

I would like to know whether it is a safe practice to subscribe multiple times (within the same C++ node) to the same topic. The purpose of this, is to assign two different callbacks to the reception of a single message.

My use case does not allow me to write all the code within a single callback (one of the callbacks is provided by external code), so I see one of two options.

  1. Use bindings (e.g. boost::bind) to compose the two callbacks. This involves complex type management, because I want a MessageType::ConstPtr, but I do not know in advance what the other callback will require (might just be a reference).
  2. Assign multiple callbacks to the same topic. This option is a lot easier to manage, but I am unsure whether it is safe, recommended, or whether it incurs a significant performance penalty.

I have already tried a simple subscriber that subscribes twice to the same topic, using different callbacks, so at least I know that it seems to work. I do not know whether there is some recommendation in favour or against this practice. Is it prone to some specific kind of bug? Does it have to create copies of the message?

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted

answered 2018-04-20 13:22:35 -0500

afsantos gravatar image

Registering multiple callbacks on the same topic seems to be a supported feature, and, thus, it should be safe.

The documentation for Subscriber states:

Once all copies of a specific Subscriber go out of scope, the subscription callback associated with that handle will stop being called. Once all Subscriber for a given topic go out of scope the topic will be unsubscribed.

This implies that there may be multiple Subscriber (i.e., multiple callbacks) on the same topic.

Indeed, looking at roscpp/topic_manager.cpp, we can see that subscribe first attempts to reuse an existing Subscription on the requested topic. If there is one, the new callback is appended to the Subscription's list of callbacks (std::vector<CallbackInfoPtr>).

Regarding any performance hits, the answer is likely within Subscription::handleMessage and Subscription::addCallback, although I still have not figured it out. It seems to matter only when the callbacks use different C++ types.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools



Asked: 2018-04-20 12:09:35 -0500

Seen: 1,015 times

Last updated: Apr 20 '18