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

Race conditions in callbacks

asked 2012-02-23 18:50:31 -0600

Conrado Miranda gravatar image

Hi, there!

I've been using ROS for a while and I just faced a possible bug. A service is called about the same time a topic got published and that topic is subscribed by the same node that implements the server.

When they run, I get a race condition, as they both use the same variable. Is it expected? I'm using python.

An example of output would be

0 1 [0.2, 0.2] 2 3 4

The list is printed inside callback for the topic and the sequence of numbers is called in the callback for the service. The service is filling the list accessed. I should be able to provide some code quite soon, as my priority is to get this working and later look for the reason (will use mutex for now).

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
9

answered 2012-02-24 00:26:46 -0600

Lorenz gravatar image

There is no guarantee in ROS that callbacks are not executed in parallel. This is desired behavior. If you want to avoid this kind of race condition, you need to use locks in your program code, i.e. when entering a callback a lock is acquired and when returning the lock is released again. That way, you get exclusive execution of callbacks. For python, you can use the threading.Lock class (tutorial). For C++ I suggest to use boost::scoped_lock.

edit flag offensive delete link more

Comments

1

You are probably right about Python, but I believe a normal C++ node or nodelet is protected against parallel callback invocations unless multi-threaded interfaces are explicitly selected. (When running multi-threaded, boost::scoped_lock is a good recommendation.)

joq gravatar image joq  ( 2012-02-24 03:42:50 -0600 )edit
1

You are right. In the default case where the user only uses ros::spin() or ros::spinOnce(), callbacks are executed sequentially. The user explicitly needs to start more spin threads or use AsyncSpinner if parallel execution of callbacks is wanted.

Lorenz gravatar image Lorenz  ( 2012-02-24 03:49:26 -0600 )edit

I thought that ROS ran in parallel, but just wanted to be sure. It's much better this way =] Thanks!

Conrado Miranda gravatar image Conrado Miranda  ( 2012-02-24 15:16:01 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2012-02-23 18:50:31 -0600

Seen: 5,823 times

Last updated: Feb 24 '12