Is it able to shutdown a Subscriber when its callback executing?
Well, I've tried to use one channel and topic A to control whether to subscribe to another topic B。So when handling B‘s callback,and in A's callback I am trying to shutdown subscriber to B , the program then block in the shutdown ,even B's callback is executed over , the shutdown method is still in block,Ctrl + C even can't kill it 。 Or in another word, is there a safe method to stop a runtime subscriber ?
Asked by sunjay on 2023-02-09 01:53:10 UTC
Answers
is there a safe method to stop a runtime subscriber
Yes: do it from outside the subscribe callback.
One approach is, In your main thread, create a "while loop", and inside the loop check a flag to determine if it should unregister the subscriber. This loop does not need to execute very often - it should spend most of its time sleeping (so you don't waste CPU cycles.) If your ros node shows 100% CPU usage, you did it wrong.
while not rospy.is_shutdown():
if stop_my_sub:
my_sub.unregister()
my_sub = None
stop_my_sub = False
rospy.sleep(0.250)
However, it is usually a bad idea for a node to unregister a subscriber. It's easy to lose messages if the node frequently subscribes & unsubscribes a topic. A better design approach is to keep the subscriber active, and have it check a flag inside the callback to determine whether to ignore the new message or to process it.
Asked by Mike Scheutzow on 2023-02-10 08:23:27 UTC
Comments
Thanks for answer and advise, I've tried this method and it did work.
Asked by sunjay on 2023-02-12 01:52:43 UTC
Comments