Iterative execution of two nodes at different rates
Hi all,
I want to execute two nodes in the same process, each one configured with its own rate. I don't want to use timers, as I want a graceful degradation if the work to do in each cycle is longer than expected. I got it using the next code, but I feel that it is quite weird. I am using an executor only to wait. Any better solution?
Component::Component(const std::string & id, float rate)
: rclcpp_lifecycle::LifecycleNode(id), rate_(rate)
{ }
void
Component::execute()
{
while (rclcpp::ok()) {
if (this->get_current_state().id() == State::PRIMARY_STATE_ACTIVE)
{
// Do some work
}
rclcpp::spin_some(this->get_node_base_interface());
rate_.sleep();
}
}
int main(int argc, char ** argv)
{
rclcpp::init(argc, argv);
rclcpp::executors::SingleThreadedExecutor executor;
auto component_1 = std::make_shared<Component>("component_1", 1);
auto component_2 = std::make_shared<Component>("component_2", 2);
std::thread{std::bind(&Component::execute, component_1)}.detach();
std::thread{std::bind(&Component::execute, component_2)}.detach();
executor.spin();
rclcpp::shutdown();
return 0;
}
Best, Francisco