(C++) How to wait for a callback to finish?

asked 2020-05-06 00:21:41 -0500

Kolohe113 gravatar image

updated 2020-05-06 01:04:45 -0500

I want to extract the size of a variable occupiedMatrix.size(), however, the size only increment in a callback function . Here is my main.cpp:

#include "get_map.h"

int main(int argc, char **argv)
{
    ros::init(argc, argv, "run");
    ros::NodeHandle nh_;
    map_class mapclass(&nh_);
    vector<vector<double> > occMap = mapclass.occupiedMatrix;
    cout<<"occMap size: "<<occMap.size()<<endl;
    ros::spin();
    return 0;
}

Initially, since mapclass has a subscriber that will increment occupiedMatrix, I thought the callback will finish before reaching

cout<<"occMap size: "<<occMap.size()<<endl;

But that is not the case, I keep getting occMap.size = 0; And the callback execute after this cout line. It there anyway to make sure my callback function finishes before I cout the size()?

Edit:

I overcame this by using spinOnce and spin, here is my new main.cpp:

int main(int argc, char **argv)
{
    ros::init(argc, argv, "run_mcl");
    ros::NodeHandle nh_;
    ros::Rate loop_rate(10);
    map_class mapclass(&nh_);
    while(ros::ok())
    {
        vector<vector<double> > occMap = mapclass.occupiedMatrix;
        if(occMap.size() > 0)
        {
            cout<<"exiting"<<endl;
            break;
        }
        ros::spinOnce();
        loop_rate.sleep();
    }
    vector<vector<double> > occMap = mapclass.occupiedMatrix;
    cout<<"occMap size: "<<occMap.size()<<endl;

    ros::spin();
    return 0;
}

I am able to get the correct size for occupiedMatrix, but is this the right way to achieve this?

edit retag flag offensive close merge delete