Last active
December 15, 2023 02:48
-
-
Save hamzamerzic/4704bbdc2e0cd46f70e6ebe188ab51ac to your computer and use it in GitHub Desktop.
[ROS] A spinner thread to force ros to spinOnce() and therefore ros services/callbacks to get invoked. Used for testing.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <ros/callback_queue.h> | |
| #include <ros/ros.h> | |
| #include <boost/thread.hpp> | |
| /* | |
| * @brief A spinner thread to force ros to spinOnce() and therefore ros services/callbacks to | |
| * get invoked etc. | |
| */ | |
| class Spinner { | |
| public: | |
| Spinner() : _run(true), _thread(boost::bind(&Spinner::spin, this)) { | |
| } | |
| ~Spinner() { | |
| _run = false; | |
| _thread.join(); | |
| } | |
| void spin() { | |
| ros::NodeHandle nh; | |
| ros::WallDuration timeout(0.1f); | |
| ros::CallbackQueue* queue = ros::getGlobalCallbackQueue(); | |
| while (nh.ok() && _run) | |
| queue->callAvailable(timeout); | |
| ros::spinOnce(); // For proper services cleanup. | |
| } | |
| private: | |
| bool _run; | |
| boost::thread _thread; | |
| }; | |
| /*----- Different way -----*/ | |
| #include <ros/ros.h> | |
| #include <boost/thread.hpp> | |
| void spinThread() { | |
| ros::spin(); | |
| } | |
| int main(int argc, char** argv) { | |
| boost::thread spin_thread(&spinThread); | |
| // Some work... | |
| ros::shutdown(); | |
| spin_thread.join(); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment