Difference between spin and rate.sleep in ROS

旧巷老猫 提交于 2020-11-30 12:55:09

问题


I am new to ROS and trying to understand this powerful tool. I am confused by the spin and rate.sleep functions. Could anyone help me with difference between those two functions and when to use which? Thanks.


回答1:


ros::spin() and ros::spinOnce() are resposible to handle communication events, e.g. arriving messages. If you are subscribing messages, services or actions you must call spin to process the events.

While ros::spinOnce() handles the events and returns immediately, ros::spin() blocks until ros invokes a shutdown. So ros::spinOnce() gives you more control if needed. More on that matter here: Callbacks and Spinning.

rate.sleep() on the other hand is merely a thread sleep with duration defined be a frequency. Here is an example

ros::Rate rate(24.);
while(ros::ok())
{
    rate.sleep();
}

This loop will be executed 24 times a second or less, depends what you do inside the loop. A ros::Rate object keeps track of how much time since last rate.sleep() was executed and sleep for the correct amount of time to hit the 24 Hz mark. See ros::Rate::sleep() API.

The equivalent way in the time domain is ros::Duration::sleep()

ros::Duration duration(1./24.);
while(ros::ok())
{
    duration.sleep();
}

Which one you use is just a matter of convenience.



来源:https://stackoverflow.com/questions/23227024/difference-between-spin-and-rate-sleep-in-ros

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!