Problem with ros::Rate sleep function

asked 2023-03-14 14:26:14 -0500

CroCo gravatar image

There seems to be a strange problem with the sleeping function for me. I've encountered it when I have two threads open at the same time. One is for the ros::Ok loop, and the other one is for getting data from a device. Basically, I need to get data from the device inside the ros::Ok loop. In this case, there is no problem since the device class has its own while loop that isn't being interrupted by the main loop. Take a look at the following code

int main(int argc, char** argv) {
ros::init(argc, argv, "project1");
ros::NodeHandle n;

double sampling(10);
ros::Rate nap(sampling); 

while( ros::ok() )
{
    cout << "--------" << endl;

    nap.sleep(); // problem 
    //std::this_thread::sleep_for(std::chrono::milliseconds(200)); // no problem
}
return 0;

}

The problem with nap.sleep() is the fact that the line '-------' is being printed out one time. I have to restart the roscore in order to resolve the issue. The problem occurs occasionally and specifically with multi-threads. However, with std::this_thread::sleep_for, I don't face any problem. I'm wondering what is the thing blocking the cout?

edit retag flag offensive close merge delete