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

Revision history [back]

click to hide/show revision 1
initial version

Your main method executes on one thread, and callbacks are called on a different thread, so you should use the python threading library to coordinate between those threads.

Since you have a data structure that you want to protect against concurrent modification, you should probably use a lock:

my_data = []
my_lock = threading.Lock()

def callback(msg):
    global my_lock
    global my_data
    with my_lock:
        # do something with my_data

while True: # main loop; or however you want to do it
    with my_lock:
        # do something else with my_data

This is just a simple example; there are lots of other examples of how to use the python threading library in the documentation, and on the internet.

You don't have to use globals for the lock, the data or the callback either they can be locals or class members.