Using Each Thread As Separate Publisher Node
I am trying to implement a multiple publisher in a Ros2 Node. And each publisher wil be in the own thread.
When I try to basic idea implementation gives me this error;
2022-07-02 13:14:16.757 [PARTICIPANT Error] Type with the same name already exists:rclinterfaces::srv::dds::GetParametersRequest -> Function registerType 2022-07-02 13:14:16.758 [PARTICIPANT Error] Type with the same name already exists:rclinterfaces::srv::dds::GetParameterTypesRequest -> Function registerType 2022-07-02 13:14:16.758 [PARTICIPANT Error] Type with the same name already exists:rclinterfaces::srv::dds::GetParameterTypesResponse -> Function registerType 2022-07-02 13:14:16.759 [PARTICIPANT Error] Type with the same name already exists:rclinterfaces::srv::dds::SetParametersRequest -> Function registerType 2022-07-02 13:14:16.759 [PARTICIPANT Error] Type with the same name already exists:rclinterfaces::srv::dds::SetParametersResponse -> Function registerType 2022-07-02 13:14:16.760 [PARTICIPANT Error] Type with the same name already exists:rclinterfaces::srv::dds::SetParametersAtomicallyRequest -> Function registerType 2022-07-02 13:14:16.762 [PARTICIPANT Error] Type with the same name already exists:rclinterfaces::srv::dds::ListParametersRequest -> Function registerType 2022-07-02 13:14:16.762 [PARTICIPANT Error] Type with the same name already exists:rclinterfaces::srv::dds::ListParametersResponse -> Function registerType
My implementation:
#include "rclcpp/rclcpp.hpp"
#include "example_interfaces/msg/string.hpp"
#include <string>
#include <thread>
class Publisher: public rclcpp::Node{
public:
Publisher(std::string name, std::string _data) : Node(name), data(_data){
publisher = this->create_publisher<example_interfaces::msg::String>("pub_topic", 10);
timer = create_wall_timer(std::chrono::milliseconds(555), std::bind(&Publisher::call_back, this));
}
private:
void call_back(){
example_interfaces::msg::String msg;
msg.data = data;
publisher->publish(msg);
}
std::string data;
std::shared_ptr<rclcpp::Publisher<example_interfaces::msg::String>> publisher;
std::shared_ptr<rclcpp::TimerBase> timer;
};
void thread_main(std::string data){
std::shared_ptr<Publisher> node = std::make_shared<Publisher>(data , data);
rclcpp::spin(node);
}
int main(int argc, char* argv[]){
rclcpp::init(argc, argv);
rclcpp::executors::MultiThreadedExecutor executor;
std::vector<std::string> dataset{"first", "second", "third", "fourth", "fifth"};
std::vector<std::thread> threads(5);
for(size_t i=0; i<dataset.size(); ++i){
threads[i] = std::thread(thread_main, dataset.at(i));
}
for(int i=0; i<10; ++i){
threads[i].join();
}
rclcpp::shutdown();
return 0;
}
Asked by mbulucay on 2022-07-02 05:31:29 UTC
Comments