38#ifndef REALTIME_TOOLS__REALTIME_PUBLISHER_H_
39#define REALTIME_TOOLS__REALTIME_PUBLISHER_H_
43#include <condition_variable>
49#include "rclcpp/publisher.hpp"
58 using PublisherSharedPtr =
typename rclcpp::Publisher<Msg>::SharedPtr;
69 : publisher_(publisher), is_running_(false), keep_running_(true), turn_(LOOP_NOT_STARTED)
71 thread_ = std::thread(&RealtimePublisher::publishingLoop,
this);
75 : is_running_(false), keep_running_(false), turn_(LOOP_NOT_STARTED) {}
81 while (is_running()) {
82 std::this_thread::sleep_for(std::chrono::microseconds(100));
84 if (thread_.joinable()) {
92 keep_running_ =
false;
94 updated_cond_.notify_one();
106 if (msg_mutex_.try_lock()) {
107 if (turn_ == REALTIME) {
126 turn_ = NON_REALTIME;
129 updated_cond_.notify_one();
145 while (!msg_mutex_.try_lock()) {
146 std::this_thread::sleep_for(std::chrono::microseconds(200));
161 bool is_running()
const {
return is_running_;}
163 void publishingLoop()
168 while (keep_running_) {
173 while (turn_ != NON_REALTIME && keep_running_) {
175 updated_cond_.wait(
lock);
178 std::this_thread::sleep_for(std::chrono::microseconds(500));
188 if (keep_running_) {publisher_->publish(outgoing);}
193 PublisherSharedPtr publisher_;
194 std::atomic<bool> is_running_;
195 std::atomic<bool> keep_running_;
199 std::mutex msg_mutex_;
202 std::condition_variable updated_cond_;
205 enum { REALTIME, NON_REALTIME, LOOP_NOT_STARTED };
206 std::atomic<int> turn_;
210using RealtimePublisherSharedPtr = std::shared_ptr<RealtimePublisher<Msg>>;