Nav2 Navigation Stack - rolling  main
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/rclcpp.hpp"
21 
22 namespace nav2
23 {
29 {
30 public:
35  explicit NodeThread(
36  rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_base)
37  : node_(node_base)
38  {
39  executor_ = std::make_shared<rclcpp::executors::SingleThreadedExecutor>();
40  thread_ = std::make_unique<std::thread>(
41  [&]()
42  {
43  executor_->add_node(node_);
44  executor_->spin();
45  executor_->remove_node(node_);
46  });
47  }
48 
53  explicit NodeThread(
54  rclcpp::executors::SingleThreadedExecutor::SharedPtr executor)
55  : executor_(executor)
56  {
57  thread_ = std::make_unique<std::thread>(
58  [&]() {
59  executor_->spin();
60  });
61  }
62 
67  template<typename NodeT>
68  explicit NodeThread(NodeT node)
69  : NodeThread(node->get_node_base_interface())
70  {}
71 
76  {
77  executor_->cancel();
78  thread_->join();
79  }
80 
81 protected:
82  rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_;
83  std::unique_ptr<std::thread> thread_;
84  rclcpp::Executor::SharedPtr executor_;
85 };
86 
87 } // namespace nav2
88 
89 #endif // NAV2_ROS_COMMON__NODE_THREAD_HPP_
A background thread to process node/executor callbacks.
Definition: node_thread.hpp:29
~NodeThread()
A destructor.
Definition: node_thread.hpp:75
NodeThread(rclcpp::executors::SingleThreadedExecutor::SharedPtr executor)
A background thread to process executor's callbacks constructor.
Definition: node_thread.hpp:53
NodeThread(rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_base)
A background thread to process node callbacks constructor.
Definition: node_thread.hpp:35
NodeThread(NodeT node)
A background thread to process node callbacks constructor.
Definition: node_thread.hpp:68