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/