How to kill a callback?
I'm having some trouble with killing my callback function properly.
I have a main node (with its own ros::NodeHandle nh
) which calls a class which initializes the following Subscriber with a ("/camera/image_raw"):
ros::NodeHandle nh;
int num = 0;
image_transport::ImageTransport it(nh);
image_transport::Subscriber sub = it.subscribe(topic, 1, imageCallback,this);
ros::spin();
The callback function in question is approximately as follows:
void imageCallback()
{
num++; //increments the global variable num
if(num < 10)
{
cv::imshow("view", cv_bridge::toCvShare(msg, "bgr8")->image);
// ... do some processing using cv_bridge and write to a folder directory
cv::imwrite(name,cv_bridge::toCvShare(msg, "bgr8")->image);
// ... the intention is that only 9 processed images are stored in this folder
// under the given name
}else if(num >= 10)
{
sub.shutdown(); // Intended to kill the subscriber once the 9th iteration is completed.
}
cv::waitKey(30);
}
My problem is that once the value of num reaches 10, the main thread appears to halt and ROS ceases to print anything to the console.
However, if I were to remove the line sub.shutdown()
, then we are still stuck inside the callback forever and we have no way of returning back to the program-flow of the main node.
How can we effectively "kill" the callback loop at its nth iteration and return back to the original node which called it?