实验程序:
talker.cc
#include <std_msgs/Int32.h>
#include <ros/ros.h>
int main(int argc, char **argv) {
ros::init(argc, argv, "talker");
ros::NodeHandle nh;
std_msgs::Int32 data;
data.data = 0;
ros::Publisher pub = nh.advertise<std_msgs::Int32>("alan_topic", 1);
ros::Rate loop_rate(1.0); // 1hz
while (ros::ok()) {
data.data++;
pub.publish(data);
std::cout << std::setprecision(12) << "[" << ros::Time::now().toSec() << "] publish " << data.data << std::endl;
loop_rate.sleep();
}
return 0;
}
listener.cc
#include <ros/ros.h>
#include <std_msgs/Int32.h>
void alan_callback(const std_msgs::Int32& data){
std::cout << std::setprecision(12) << "[" << ros::Time::now().toSec() << "] process " << data.data << " short time" << std::endl;
std::cout << std::setprecision(12) << "[" << ros::Time::now().toSec() << "] process " << data.data << " long time" << std::endl;
return;
}
int main(int argc, char ** argv) {
ros::init(argc, argv, "listener");
ros::NodeHandle nh;
ros::Subscriber sub = nh.subscribe("alan_topic", 1, alan_callback);
ros::spin();
return 0;
}
实时
listener.cc
#include <unistd.h>
#include <ros/ros.h>
#include <std_msgs/Int32.h>
void alan_callback(const std_msgs::Int32& data){
std::cout << std::setprecision(12) << "[" << ros::Time::now().toSec() << "] process " << data.data << " short time" << std::endl;
std::cout << std::setprecision(12) << "[" << ros::Time::now().toSec() << "] process " << data.data << " long time" << std::endl;
sleep(5); // 5秒
return;
}
int main(int argc, char ** argv) {
ros::init(argc, argv, "listener");
ros::NodeHandle nh;
ros::Subscriber sub = nh.subscribe("alan_topic", 1, alan_callback);
ros::spin();
return 0;
}
回调函数处理时间长导致数据丢失(队列长度为1ÿ