ROS 2 rclcpp + rcl - humble  humble
ROS 2 C++ Client Library with ROS Client Library
write_preferring_read_write_lock.hpp
1 // Copyright 2020 Open Source Robotics Foundation, Inc.
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 RCLCPP__WAIT_SET_POLICIES__DETAIL__WRITE_PREFERRING_READ_WRITE_LOCK_HPP_
16 #define RCLCPP__WAIT_SET_POLICIES__DETAIL__WRITE_PREFERRING_READ_WRITE_LOCK_HPP_
17 
18 #include <condition_variable>
19 #include <functional>
20 #include <mutex>
21 
22 #include "rclcpp/visibility_control.hpp"
23 
24 namespace rclcpp
25 {
26 namespace wait_set_policies
27 {
28 namespace detail
29 {
30 
32 
171 {
172 public:
173  RCLCPP_PUBLIC
174  explicit WritePreferringReadWriteLock(std::function<void()> enter_waiting_function = nullptr);
175 
177 
180  class RCLCPP_PUBLIC ReadMutex
181  {
182 public:
183  void
184  lock();
185 
186  void
187  unlock();
188 
189 protected:
190  explicit ReadMutex(WritePreferringReadWriteLock & parent_lock);
191 
192  WritePreferringReadWriteLock & parent_lock_;
193 
194  friend class WritePreferringReadWriteLock;
195  };
196 
198 
201  class RCLCPP_PUBLIC WriteMutex
202  {
203 public:
204  void
205  lock();
206 
207  void
208  unlock();
209 
210 protected:
211  explicit WriteMutex(WritePreferringReadWriteLock & parent_lock);
212 
213  WritePreferringReadWriteLock & parent_lock_;
214 
215  friend class WritePreferringReadWriteLock;
216  };
217 
219  RCLCPP_PUBLIC
220  ReadMutex &
221  get_read_mutex();
222 
224  RCLCPP_PUBLIC
225  WriteMutex &
226  get_write_mutex();
227 
228 protected:
229  bool reader_active_ = false;
230  std::size_t number_of_writers_waiting_ = 0;
231  bool writer_active_ = false;
232  std::mutex mutex_;
233  std::condition_variable condition_variable_;
234  ReadMutex read_mutex_;
235  WriteMutex write_mutex_;
236  std::function<void()> enter_waiting_function_;
237 };
238 
239 } // namespace detail
240 } // namespace wait_set_policies
241 } // namespace rclcpp
242 
243 #endif // RCLCPP__WAIT_SET_POLICIES__DETAIL__WRITE_PREFERRING_READ_WRITE_LOCK_HPP_
RCLCPP_PUBLIC WriteMutex & get_write_mutex()
Return write mutex which can be used with standard constructs like std::lock_guard.
RCLCPP_PUBLIC ReadMutex & get_read_mutex()
Return read mutex which can be used with standard constructs like std::lock_guard.
Versions of rosidl_typesupport_cpp::get_message_type_support_handle that handle adapted types.