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

how to use multi-threads (user-input, subscriber and srv-client)?

asked 2022-01-03 11:25:48 -0500

jorosuser gravatar image

updated 2022-01-03 13:10:48 -0500

Hi, I am using ROS2 foxy and I am struggling with simultanious execution of some code (that is somehow dependend on each other).


I want a node, that simultaniously runs a loop with user Input/Output, acts as a client for a service (takes a few seconds) and is also able to recieve messages over a topic.

more detailed:

I want to make a "task-control-unit" which is a class named CTaskControl inheriting from rclcpp::node. It has a method mUserInterface which accepts user-inputs to start some other Methods (if the user want to start them). It should also subscribe to a topic to recieve some data. And it should also, once in a while start a service and wait for the response.

I am trying to start a thread in the constructor of CTaskControl with pthread_create(&mUiThreadId, NULL, &mUserInterface, NULL); but then I need to make the method static, which then don't allow to call methods with this-><...method-to-start-service-etc...>.

I am not sure if I miss something or if there is a completely other solution which makes everything easier.. I also thought about adding several nodes to an executor and spin them, but then I have a problem with the communication between the threads because how do I start a method from another class then?

In the foxy tutorials there are always examples for only one subscriber, client, etc. but I didn't find an example how to combine them. I would appreciate any hints :)

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2022-01-03 13:41:46 -0500

jorosuser gravatar image

updated 2022-01-03 13:44:15 -0500

Okay, I found a solution to start a class method in a seperate thread. I did not use pthread_create, but instead std::thread.

the class is called CTaskControl and the Method is called mUserInterface.

Inside the constructor of the class, I started the Method (which containes a while-loop) like this:

std::thread{std::bind(&CTaskControl::mUserInterface, this)}.detach();

Now the node can receive messages and execute a while-loop at the same time.

edit flag offensive delete link more



Thank you for taking to document your answer

osilva gravatar image osilva  ( 2022-01-03 17:44:09 -0500 )edit

Question Tools



Asked: 2022-01-03 11:25:48 -0500

Seen: 116 times

Last updated: Jan 03 '22