how to write a thread in ROS
I would like to know how to write a async thread in ROS. An example would be greatly appreciated. Edwin
ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange |
I would like to know how to write a async thread in ROS. An example would be greatly appreciated. Edwin
Assuming you are looking for C++ solution, here is what the Wiki page on Callbacks and Spinning says:
roscpp does not try to specify a threading model for your application. This means that while roscpp may use threads behind the scenes to do network management, scheduling etc., it will never expose its threads to your application. roscpp does, however, allow your callbacks to be called from any number of threads if that's what you want.
Please also see this question with answers.
In short: you can choose any threading library you like; ROS nodes and callbacks are thread-safe. However, to avoid extra dependencies it is a good idea to use Boost threads (ROS utilises Boost for many internal components).
Here are the docs and examples for Boost threads. Also, if c++11 compiler is available then you can try std::thread. Or you even can use POSIX Threads.
EDIT:
The following example uses Boost threads with ROS. It publishes empty messages to two topics with different rates, which you can easily check with rostopic hz <topic_name>
.
#include <ros/ros.h>
#include <std_msgs/Empty.h>
#include <boost/thread/thread.hpp>
void do_stuff(int* publish_rate)
{
ros::NodeHandlePtr node = boost::make_shared<ros::NodeHandle>();
ros::Publisher pub_b = node->advertise<std_msgs::Empty>("topic_b", 10);
ros::Rate loop_rate(*publish_rate);
while (ros::ok())
{
std_msgs::Empty msg;
pub_b.publish(msg);
loop_rate.sleep();
}
}
int main(int argc, char** argv)
{
int rate_b = 1; // 1 Hz
ros::init(argc, argv, "mt_node");
// spawn another thread
boost::thread thread_b(do_stuff, &rate_b);
ros::NodeHandlePtr node = boost::make_shared<ros::NodeHandle>();
ros::Publisher pub_a = node->advertise<std_msgs::Empty>("topic_a", 10);
ros::Rate loop_rate(10); // 10 Hz
while (ros::ok())
{
std_msgs::Empty msg;
pub_a.publish(msg);
loop_rate.sleep();
// process any incoming messages in this thread
ros::spinOnce();
}
// wait the second thread to finish
thread_b.join();
return 0;
}
Asked: 2015-09-21 08:59:43 -0600
Seen: 17,644 times
Last updated: Sep 21 '15