ros2_cookbook icon indicating copy to clipboard operation
ros2_cookbook copied to clipboard

Thread daemon seems to cause "terminate called without an active exception"

Open PaulBouchier opened this issue 1 year ago • 0 comments

The idea of making a daemon thread so rate.sleep() doesn't get stuck seems good, but seems to have the side-effect of causing this output after rclpy.shutdown() is called:

terminate called without an active exception [ros2run]: Aborted

Reading the web indicates that it's caused by a running thread having to be aborted when the process shuts down. I propose a more conventional approach is needed - something like:

class my_class
__init__(self):
        # Run spin in a thread so Rate.sleep() works
        self.thread = threading.Thread(target=self.spin_thread)
        self.stop_thread_flag = False
        self.thread.start()

def spin_thread(self):
    # implement a thread that keeps calling spin_once() so rate.sleep() will work
    def spin_thread(self):
        while(self.stop_thread_flag == False and rclpy.ok()):
            rclpy.spin_once(self, timeout_sec=0.1)
            if (self.stop_thread_flag):
                return

main():
    # Destroy the node explicitly
    # (optional - otherwise it will be done automatically
    # when the garbage collector destroys the node object)
    my_class.stop_thread_flag = True
    time.sleep(0.2)
    move_parent.destroy_node()
    rclpy.shutdown()

The disadvantage is you need to wait for the thread to exit before shutting things down. But it seems better than exiting with an abort.

Thoughts?

PaulBouchier avatar Jan 12 '24 12:01 PaulBouchier