38 #ifndef REALTIME_TOOLS__REALTIME_BUFFER_H_
39 #define REALTIME_TOOLS__REALTIME_BUFFER_H_
54 non_realtime_data_ =
new T();
55 realtime_data_ =
new T();
66 non_realtime_data_ =
new T(data);
67 realtime_data_ =
new T(data);
72 if (non_realtime_data_) {
73 delete non_realtime_data_;
76 delete realtime_data_;
80 RealtimeBuffer(
const RealtimeBuffer & source)
83 non_realtime_data_ =
new T();
84 realtime_data_ =
new T();
87 writeFromNonRT(*source.readFromNonRT());
95 if (
this == &source) {
100 writeFromNonRT(*source.readFromNonRT());
108 std::unique_lock<std::mutex> guard(mutex_, std::try_to_lock);
109 if (guard.owns_lock()) {
111 if (new_data_available_) {
112 T * tmp = realtime_data_;
113 realtime_data_ = non_realtime_data_;
114 non_realtime_data_ = tmp;
115 new_data_available_ =
false;
118 return realtime_data_;
121 T * readFromNonRT()
const
123 std::lock_guard<std::mutex> guard(mutex_);
125 if (new_data_available_) {
126 return non_realtime_data_;
128 return realtime_data_;
132 void writeFromNonRT(
const T & data)
135 std::lock_guard<std::mutex> guard(mutex_);
137 std::unique_lock<std::mutex> guard(mutex_, std::defer_lock);
138 while (!guard.try_lock()) {
139 std::this_thread::sleep_for(std::chrono::microseconds(500));
144 *non_realtime_data_ = data;
145 new_data_available_ =
true;
148 void initRT(
const T & data)
150 *non_realtime_data_ = data;
151 *realtime_data_ = data;
157 if (non_realtime_data_) {
158 delete non_realtime_data_;
160 if (realtime_data_) {
161 delete realtime_data_;
165 non_realtime_data_ =
new T();
166 realtime_data_ =
new T();
171 T * non_realtime_data_;
172 bool new_data_available_;
175 mutable std::mutex mutex_;