1
$\begingroup$

I'm trying to write a python node, which has one class and two member functions as callback functions. so a TimeSynchronizer and Subscriber in a node. I saw in this link and tested that python subscribers are event-driven model and are in separate threads. How to get a python node in ROS subscribe to multiple topics?

My question here is , are they thread safe when they are working on the same class member? e.g. self.a below. Do I need to write a lock? Where can I find more information about this? Thank you in advanced!!!!

class mr_listener(object):

def __init__(self):
    self.a =  [1,2,3,4,5]
    rospy.init_node('mr_listener', anonymous=True)
    scan_subscriber = message_filters.Subscriber('/scan',LaserScan)
    pose_subscriber = message_filters.Subscriber('/slam_out_pose', PoseStamped)
    ts = message_filters.ApproximateTimeSynchronizer([scan_subscriber,projected_scan_subscriber,pose_subscriber], 10, 0.1, allow_headerless=True)
    ts.registerCallback(self.callback1)
    rospy.Subscriber("chatter", String, self.callback2)
    rospy.spin()

def callback1(self,scan,pose):
    somthing

def callback2(self,chatt):
    somingthing
    rospy.sleep(1.)
$\endgroup$
0
$\begingroup$

For a particular topic, there is only one thread that all the subscribers share.

Each service callback does get its own thread because there can only be one service callback for a particular service.

Future versions of rospy will likely have a different, more versatile threading model for subscriptions.

rospy.spin() is a built-in asynchronous method in contrast with roscpp::spin() which is single thread (roscpp::AsyncSpinner() is async).

Callbacks in rospy in general is they're essentially handled sequentially during calls to Sleep and Spin, meaning they're implicitly threadsafe and I can modify the same data from multiple callbacks within a node without locks or other safeguards.

Unfortunately, no. Unlike roscpp, rospy creates a new thread for every Subscriber and Timer. In fact, rospy.spin() is just an infinite loop of half-second waits. As such, callbacks in rospy are not threadsafe. You should use locks in any rospy node where multiple callbacks of any kind might interact.

$\endgroup$

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.