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

roscpp service calls - multithreading

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

JoshMarino gravatar image

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

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("Ready to compute Descartes trajectory.");  

  // Keep ROS service running until it is shutdown

  return 0;
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

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

DavidN gravatar image

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

It seems this question is about multithreading in ROS. There are a few ways to do this. You can take a look at:

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

   while (ros::ok()) {
     //Do any periodical work here


   return 0;
edit flag offensive delete link more



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 -0500 )edit

Question Tools

1 follower


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

Seen: 2,269 times

Last updated: Apr 11 '17