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

Possibility of data race in subscriber callback(s)?

asked 2019-04-21 13:48:12 -0500

EdwardNur gravatar image

updated 2019-04-22 09:00:31 -0500

gvdhoorn gravatar image

I have a question on how does the ros::subscriber work. For example, if I have a class and inside that class I constantly update a specific variable in a while loop:

while(ros::ok()) _effort = this->getEffort();

What will happen if this same class has a subscriber callback function which also writes into this _effort variable? Does it have some kind of a memory lock enabled?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2019-04-21 19:25:27 -0500

Short answer: no, there is not a memory race (in terms of two threads writing to the same memory address at the same time). By default, ROS doesn't start any threads when you make subscribers/callbacks. When you call ros::spin() or ros::spinOnce(), it will call each of the subscribers you have added sequentially, in the same thread as the spin.

Note about your code: if the while(ros::ok()) _effort = this->getEffort(); is running in the main loop, then your subscribers will never get called, since (as mentioned above), in a single threaded program, subscribers are only called when ros::spin() or ros::spinOnce() is called. A slight modification to your above code that would call the subscriber would be:

while(ros::ok()) {
    _effort = this->getEffort();

Now if you are creating a different thread to run the while(ros::ok()) _effort = this->getEffort();, then yes, there will be a data race, as ROS doesn't handle memory locks for you. For some more resources on this, look around ROS answers some more (here's one).

Source: mostly from .

edit flag offensive delete link more

Question Tools



Asked: 2019-04-21 13:48:12 -0500

Seen: 329 times

Last updated: Apr 22 '19