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

Is it able to shutdown a Subscriber when its callback executing? [closed]

asked 2023-02-09 00:53:10 -0500

sunjay gravatar image

updated 2023-02-09 21:17:21 -0500

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 ?

edit retag flag offensive reopen merge delete

Closed for the following reason the question is answered, right answer was accepted by sunjay
close date 2023-02-15 03:38:34.086666

1 Answer

Sort by » oldest newest most voted
1

answered 2023-02-10 07:23:27 -0500

Mike Scheutzow gravatar image

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.

edit flag offensive delete link more

Comments

Thanks for answer and advise, I've tried this method and it did work.

sunjay gravatar image sunjay  ( 2023-02-12 00:52:43 -0500 )edit

Question Tools

1 follower

Stats

Asked: 2023-02-09 00:53:10 -0500

Seen: 173 times

Last updated: Feb 10 '23