ros::spin() 单线程回调函数
ros::spin()在节点关闭或ros::shutdown()或按下Ctrl-C才会返回。
ros::spinOnce() 单线程回调函数
ros::spinOnce()在那个时间点,会调用所有的回调函数。
ros::MultiThreadedSpinner 防阻塞多线程回调函数
MultiThreadedSpinner类似于ros::spin(),在构造过程中可以指定它所用线程数,但如果不指定线程数或者线程数设置为0,它将在每个cpu内核开辟一个线程。
用法如下:
ros::MultiThreadedSpinner spinner(4); // Use 4 threads
spinner.spin(); // spin() will not return until the node has been shutdown
ros::AsyncSpinner 防阻塞多线程回调函数
AsyncSpinner比MultiThreadedSpinner更优,它有start() 和stop() 函数,并且在销毁的时候会自动停止。
下面的用法等价于上面的MultiThreadedSpinner例子。
ros::AsyncSpinner spinner(4); // Use 4 threads
spinner.start();
spinner.stop();
ros::waitForShutdown();
建议
A callback should stay as simple and fast as possible.
In most of the cases, a callback is just feeding ROS data to your own classes which is usually as simple as copying data (and maybe converting them). It will help you ensuring that your callbacks are thread-safe (if you want to convert your node to a nodelet for instance, one day) and avoid making "ros::Spin" blocking for a long time, even in the case you are using the single-threaded spinner.
参考
https://wiki.ros.org/roscpp/Overview/Callbacks%20and%20Spinning
https://answers.ros.org/question/53055/ros-callbacks-threads-and-spinning/