Nav2 Navigation Stack - lyrical  lyrical
ROS 2 Navigation Stack
node_thread.hpp
1 // Copyright (c) 2019 Intel Corporation
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifndef NAV2_ROS_COMMON__NODE_THREAD_HPP_
16 #define NAV2_ROS_COMMON__NODE_THREAD_HPP_
17 
18 #include <memory>
19 
20 #include "rclcpp/executor.hpp"
21 #include "rclcpp/executors/single_threaded_executor.hpp"
22 #include "rclcpp/node_interfaces/node_base_interface.hpp"
23 
24 namespace nav2
25 {
31 {
32 public:
37  explicit NodeThread(
38  rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_base)
39  : node_(node_base)
40  {
41  executor_ = std::make_shared<rclcpp::executors::SingleThreadedExecutor>();
42  thread_ = std::make_unique<std::thread>(
43  [&]()
44  {
45  executor_->add_node(node_);
46  executor_->spin();
47  executor_->remove_node(node_);
48  });
49  }
50 
55  explicit NodeThread(
56  rclcpp::executors::SingleThreadedExecutor::SharedPtr executor)
57  : executor_(executor)
58  {
59  thread_ = std::make_unique<std::thread>(
60  [&]() {
61  executor_->spin();
62  });
63  }
64 
69  template<typename NodeT>
70  explicit NodeThread(NodeT node)
71  : NodeThread(node->get_node_base_interface())
72  {}
73 
78  {
79  executor_->cancel();
80  thread_->join();
81  }
82 
83 protected:
84  rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_;
85  std::unique_ptr<std::thread> thread_;
86  rclcpp::Executor::SharedPtr executor_;
87 };
88 
89 } // namespace nav2
90 
91 #endif // NAV2_ROS_COMMON__NODE_THREAD_HPP_
A background thread to process node/executor callbacks.
Definition: node_thread.hpp:31
~NodeThread()
A destructor.
Definition: node_thread.hpp:77
NodeThread(rclcpp::executors::SingleThreadedExecutor::SharedPtr executor)
A background thread to process executor's callbacks constructor.
Definition: node_thread.hpp:55
NodeThread(rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_base)
A background thread to process node callbacks constructor.
Definition: node_thread.hpp:37
NodeThread(NodeT node)
A background thread to process node callbacks constructor.
Definition: node_thread.hpp:70