15 #include "rclcpp/executors/multi_threaded_executor.hpp"
22 #include "rcpputils/scope_exit.hpp"
24 #include "rclcpp/utilities.hpp"
28 MultiThreadedExecutor::MultiThreadedExecutor(
30 size_t number_of_threads,
31 bool yield_before_execute,
32 std::chrono::nanoseconds next_exec_timeout)
34 yield_before_execute_(yield_before_execute),
35 next_exec_timeout_(next_exec_timeout)
37 number_of_threads_ = number_of_threads ? number_of_threads : std::thread::hardware_concurrency();
38 if (number_of_threads_ == 0) {
39 number_of_threads_ = 1;
43 MultiThreadedExecutor::~MultiThreadedExecutor() {}
49 throw std::runtime_error(
"spin() called while already spinning");
51 RCPPUTILS_SCOPE_EXIT(this->
spinning.store(
false); );
52 std::vector<std::thread> threads;
55 std::lock_guard wait_lock{wait_mutex_};
56 for (; thread_id < number_of_threads_ - 1; ++thread_id) {
57 auto func = std::bind(&MultiThreadedExecutor::run,
this, thread_id);
58 threads.emplace_back(func);
63 for (
auto & thread : threads) {
69 MultiThreadedExecutor::get_number_of_threads()
71 return number_of_threads_;
75 MultiThreadedExecutor::run(
size_t this_thread_number)
77 (void)this_thread_number;
81 std::lock_guard wait_lock{wait_mutex_};
85 if (!get_next_executable(any_exec, next_exec_timeout_)) {
89 if (yield_before_execute_) {
90 std::this_thread::yield();
97 any_exec.callback_group.reset();
Coordinate the order and timing of available communication tasks.
std::shared_ptr< rclcpp::Context > context_
The context associated with this executor.
RCLCPP_PUBLIC void execute_any_executable(AnyExecutable &any_exec)
Find the next available executable and do the work associated with it.
std::atomic_bool spinning
Spinning state, used to prevent multi threaded calls to spin and to cancel blocking spins.
RCLCPP_PUBLIC void spin() override
Versions of rosidl_typesupport_cpp::get_message_type_support_handle that handle adapted types.
RCLCPP_PUBLIC bool ok(rclcpp::Context::SharedPtr context=nullptr)
Check rclcpp's status.
Options to be passed to the executor constructor.