0
$\begingroup$

Rosanswers logo

I would like to know how to write a async thread in ROS. An example would be greatly appreciated. Edwin


Originally posted by elthef on ROS Answers with karma: 26 on 2015-09-21

Post score: 1

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

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;
}

Originally posted by Boris with karma: 3060 on 2015-09-21

This answer was ACCEPTED on the original site

Post score: 4


Original comments

Comment by elthef on 2015-09-25:
Thank you i will try it out

Comment by mrtwister on 2016-03-25:
Was it working with this?

$\endgroup$

Your Answer

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