Ask Your Question
0

Possibility of data race in subscriber callback(s)?

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

EdwardNur gravatar image

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

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
0

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

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()) {
    ros::spinOnce();
    _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 http://wiki.ros.org/roscpp/Overview/C... .

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

2 followers

Stats

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

Seen: 43 times

Last updated: Apr 22