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

How to wait a method until a callback finishes?

asked 2018-11-04 16:52:13 -0500

Ivan_Sanchez gravatar image

Hi all,

I'm trying to stop a method until a particular callback is executed, because this method uses data that is updated in the callback, but I don't know how to do this task. I'm using ros kinetic and python.

Thanks for your help!!

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2018-11-04 19:41:35 -0500

ahendrix gravatar image

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.

edit flag offensive delete link more

Comments

Is there something similar for C++ nodes?

kosmastsk gravatar image kosmastsk  ( 2019-04-05 16:39:06 -0500 )edit

Yes. C++11 and newer have std::mutex and std::unique_lock . On older versions of C++, you can use boost::mutex.

ahendrix gravatar image ahendrix  ( 2019-04-05 21:55:06 -0500 )edit

Thanks a lot! :)

kosmastsk gravatar image kosmastsk  ( 2019-04-09 15:14:41 -0500 )edit

Question Tools

2 followers

Stats

Asked: 2018-11-04 16:52:13 -0500

Seen: 3,604 times

Last updated: Nov 04 '18