ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
0

roscpp service calls - multithreading

asked 2017-04-10 17:02:51 -0600

JoshMarino gravatar image

updated 2017-04-11 09:34:31 -0600

I have a service created in C++ that only handles one request at a time. Normally this would not be a problem, but my service is computing a Descartes trajectory, which takes somewhere between 3-8 seconds. Is there a way to thread the service requests such that they are taking place at the same time instead of one after the other?

Here is the current implementation of my service.

int main(int argc, char **argv)
{
  // Initialize node
  ros::init(argc, argv, "compute_descartes_traj_server");
  ros::NodeHandle node_handle;  

  // Create subscriber to /joint_states topic
  Listener listener;
  ros::Subscriber sub = node_handle.subscribe("joint_states", 10, &Listener::jointStatesCallback, &listener);

  // Create ComputeDescartesTraj service
  ros::ServiceServer service = node_handle.advertiseService("compute_descartes_traj", &Listener::ComputeDescartesTraj, &listener);
  ROS_INFO("-----------------------------------------------");
  ROS_INFO("Ready to compute Descartes trajectory.");  
  ROS_INFO("-----------------------------------------------");

  // Keep ROS service running until it is shutdown
  ros::spin();

  return 0;
 }
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2017-04-10 21:15:09 -0600

DavidN gravatar image

updated 2017-04-10 21:15:46 -0600

It seems this question is about multithreading in ROS. There are a few ways to do this. You can take a look at: http://wiki.ros.org/roscpp/Overview/C...

Below is a minimal example with AsyncSpinner:

int main(int argc, char **argv) {
   ros::init(argc, argv, "your_node");

   //Any init here

   ros::Rate loop_rate(10.0); //Choose the loop rate
   ros::AsyncSpinner spinner(10); //Choose how many threads
   spinner.start();

   while (ros::ok()) {
     //Do any periodical work here
     ros::spinOnce();
     loop_rate.sleep();
   }

   ros::waitForShutdown();

   return 0;
}
edit flag offensive delete link more

Comments

1

This will work, but make sure that your service handlers are either idempotent or use proper locking of resources if you run them in parallel.

gvdhoorn gravatar image gvdhoorn  ( 2017-04-11 11:43:08 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2017-04-10 17:02:51 -0600

Seen: 2,380 times

Last updated: Apr 11 '17