ROS Resources: Documentation | Support | Discussion Forum | Service Status | Q&A
Ask Your Question

Race conditions in callbacks

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

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

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

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


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 imagejoq ( 2012-02-24 03:42:50 -0500 )edit

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 imageLorenz ( 2012-02-24 03:49:26 -0500 )edit

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

Conrado Miranda gravatar imageConrado Miranda ( 2012-02-24 15:16:01 -0500 )edit

Your Answer

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

Add Answer

The deadline to submit a proposal to present at ROSCon 2017 is June 25, 2017. Submit yours now!

Question Tools


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

Seen: 2,263 times

Last updated: Feb 24 '12