0
$\begingroup$

Rosanswers logo

In my case, I'm having multiple threads to subscribe to different topics. I'm not able to receive the data from any. I'm assuming its because I'm using the same node handler for all threads. But I did read and learn that each node can have only one handler, can I get some clarification on this ?

I am using boost threads. A code snippet explaining would be of great help as well.


Edit: Thank you. I had followed this link. Below is my code snippet.

void chatterCallback(const std_msgs::String::ConstPtr& msg)
{
 ROS_INFO("I heard: [%s]", msg->data.c_str());
}

void thread1(ros::NodeHandle &n)
{

    ros::Subscriber sub1 = n.subscribe("msg1", 1000, chatterCallback);
}

void thread2(ros::NodeHandle &n)
{

    ros::Subscriber sub2 = n.subscribe("msg2", 1000, chatterCallback);
}

int main(int argc, char **argv)
{

 ros::init(argc, argv, "example");

 ros::NodeHandle n;
 
 boost::thread get_speedData_thread(&thread1, n);

 boost::thread get_encoderData_thread(&thread2, n);
    
 ros::MultiThreadedSpinner spinner(2);
 spinner.spin();
    

 get_speedData_thread.join();   
 get_encoderData_thread.join();
 
 return 0;
}

I'm publishing msg1 and msg2 from other nodes. And I'm using Multithreaded spinner. My callback function is just a display function. Can anyone tell me where is the error. Message is not getting displayed.

Thanks in advance.


Originally posted by asdfgf on ROS Answers with karma: 42 on 2016-05-24

Post score: 0

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

ROS can handle the threads for you.
http://wiki.ros.org/roscpp/Overview/Callbacks%20and%20Spinning

When a subscriber goes out of scope, the subscription is canceled. See the fix below. This will service the callbacks with two threads.

void chatterCallback(const std_msgs::String::ConstPtr& msg)
{
 ROS_INFO("I heard: [%s]", msg->data.c_str());
}

int main(int argc, char **argv)
{
 ros::init(argc, argv, "example");
 
 ros::NodeHandle n;
 ros::Subscriber sub1 = n.subscribe("msg1", 1000, chatterCallback);
 ros::Subscriber sub2 = n.subscribe("msg2", 1000, chatterCallback);

 ros::MultiThreadedSpinner spinner(2);
 spinner.spin();

 return 0;
}

Originally posted by kmhallen with karma: 1416 on 2016-05-25

This answer was ACCEPTED on the original site

Post score: 1


Original comments

Comment by asdfgf on 2016-05-25:
I tried this. I have updated my question.

Comment by asdfgf on 2016-05-26:
Thank you. It worked. But the threads are running very slowly even though my ros::Rate is set to 0.001. Can I know how can I make it fast enough to publish and subscribe in real time ?

It is taking about two minutes to subscribe on one topic.

Pardon me, I'm a newbie in this.

Comment by kmhallen on 2016-05-30:
If you have a different question, please start a new question.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.