Robotics StackExchange | Archived questions

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

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


summary:

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 :)

Asked by jorosuser on 2022-01-03 12:25:48 UTC

Comments

Answers

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.

Asked by jorosuser on 2022-01-03 14:41:46 UTC

Comments

Thank you for taking to document your answer

Asked by osilva on 2022-01-03 18:44:09 UTC