转载:[https://blog.youkuaiyun.com/jixiangwangzi/article/details/126585521 ]
结论:
ROS2 的 node中使用的如果node不添加到spin中,则timer、service、action等的callback函数无法正常回调。
但是如果在service、action调用之后,调用如下函数则可正常回调。原因是spin_until_future_complete函数内部会创建一个executor,添加nh_这个Node
rclcpp::spin_until_future_complete(this->get_node_base_interface(), future_goal_handle, std::chrono::seconds(5));
1.node的构成
rclcpp::Node的成员变量有一些interface,例如
node_base:可以记录node的基本状态,例如:
node的name;
node的call_back_group
node的associated_with_executor_,即是否与executor绑定,以此确定只跟一个executor有关系
node_graph
node_services
node_topics:显而易见用来创建publisher,subscriber等
2.executor
用来在node 调用spin(内部循环)时,执行node内部的callback函数。
一个executor可以添加多个node,及为不同的node执行callback函数
executor分singleThreadExecutor和multiThreadExecutor。即单线程执行和多线程执行。
singleThreadExecutor添加多个node时,顺序执行call_back
multiThreadExecutor添加多个node时,多线程执行call_back
一个node只能被一个executor添加,
在executor.add(node)函数中会检查
node是否已经被其他executor添加(即查看node.node_base.associated_with_executor_是否为true)
或node是否已被此executor添加过
3.出错的程序
3.1 node_main.cpp,正常执行
rclcpp::init(argc, argv);
rclcpp::executors::SingleThreadedExecutor executor;
auto node = std::make_shared<robotis::localization::LocalizationNode>(rclcpp::NodeOptions());
executor.add_node(node);
std::atomic_bool & has_executor = node->get_node_base_interface()->get_associated_with_executor_atomic(