Turtlesim /spawn service error : rcl node's context is invalid
I am using ros2 foxy, and I get this error when trying to call the /spawn service from the turtlesim_node :
"terminate called after throwing an instance of 'rclcpp::exceptions::RCLError' what(): could not create client: rcl node's context is invalid, at /tmp/binarydeb/ros-foxy-rcl-1.1.11/src/rcl/node.c:441"
Does anyone has an idea about this error ?
Here is my code :
#include "rclcpp/rclcpp.hpp"
#include "turtlesim/srv/spawn.hpp"
class MyturtleSpawner : public rclcpp::Node {
public:
MyturtleSpawner() : Node("turtle_spawner"){
threadV_.push_back(std::thread(std::bind(&MyturtleSpawner::callSpawnClient, this, 1.0, 1.0, 0.0)));
}
void callSpawnClient(float, float, float);
private:
std::vector<std::thread> threadV_;
};
void MyturtleSpawner::callSpawnClient(float x, float y, float theta){
auto spawnClient = this->create_client<turtlesim::srv::Spawn>("spawn");
while (!spawnClient->wait_for_service(std::chrono::seconds(1))){
RCLCPP_INFO(this->get_logger(), "Waiting for the Spawn server to respond ...");
}
auto spawnRequest = std::make_shared<turtlesim::srv::Spawn::Request>();
spawnRequest->x = x;
spawnRequest->y = y;
spawnRequest->theta = theta;
auto future = spawnClient->async_send_request(spawnRequest);
try{
auto spawnResponse = future.get();
RCLCPP_INFO(this->get_logger(), "Turtle Spawned Successfully : %s", spawnResponse->name);
}
catch(const std::exception& e){
RCLCPP_ERROR(this->get_logger(), "Spawn service call failed !");
}
}
int main(int argc, char **argv)
{
rclcpp::init(argc, argv);
auto node = std::make_shared<MyturtleSpawner>();
rclcpp::shutdown();
return 0;
}