Robotics StackExchange | Archived questions

How to stop SingleThreadedExecutor::spin() ?

ROS2 crystal, Ubuntu 18 x64.

Hello, I faced a problem with stopping a thread with SingleThreadedExecutor::spin() inside. The last string is never printed... the only way to solve - uncomment sleep(1)

1) Why spin() is blocked if no actual work ?(no nodes added to SingleThreadedExecutor)

2) How to stop it correctly? Probably cancel() is executed before the spin() call.

   class test_class {
     public:
       test_class() {
       }
       ~test_class() {
         st_executor_.cancel();
         if (st_thread_.joinable())
           st_thread_.join();

       }
       void run() {
         st_thread_ = std::thread([this]() {
           st_executor_.spin();
         });
       }
     private:
       rclcpp::executors::SingleThreadedExecutor st_executor_;
       std::thread st_thread_;
   };

   int main(int argc, char ** argv) {
     rclcpp::init(argc, argv);
     do {
       test_class tc;
       tc.run();
       //sleep(1);
     }
     while (0);
     std::cout << "This string is never printed" << std::endl;

   }

Asked by alga19 on 2019-03-06 10:18:53 UTC

Comments

Answers

1) Why spin() is blocked if no actual work ?(no nodes added to SingleThreadedExecutor)

Because spin() will block forever until it is canceled by either SIGINT or executor.cancel().

2) How to stop it correctly? Probably cancel() is executed before the spin() call.

You probably need to ensure cancel() is called after spin(). I'm not sure if calling cancel() before spin() will cause the first spin() to wake up or not, but my guess is that it would.

Asked by William on 2019-03-06 16:21:39 UTC

Comments

Ok, understood. Thank you.

Asked by alga19 on 2019-03-07 07:58:37 UTC

Ok, understood. Thank you.

Asked by alga19 on 2019-03-07 07:59:01 UTC