Program Listing for File write_preferring_read_write_lock.hpp

Return to documentation for file (include/rclcpp/wait_set_policies/detail/write_preferring_read_write_lock.hpp)

// Copyright 2020 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef RCLCPP__WAIT_SET_POLICIES__DETAIL__WRITE_PREFERRING_READ_WRITE_LOCK_HPP_
#define RCLCPP__WAIT_SET_POLICIES__DETAIL__WRITE_PREFERRING_READ_WRITE_LOCK_HPP_

#include <condition_variable>
#include <functional>
#include <mutex>

#include "rclcpp/visibility_control.hpp"

namespace rclcpp
{
namespace wait_set_policies
{
namespace detail
{


class WritePreferringReadWriteLock final
{
public:
  RCLCPP_PUBLIC
  explicit WritePreferringReadWriteLock(std::function<void()> enter_waiting_function = nullptr);


  class RCLCPP_PUBLIC ReadMutex
  {
public:
    void
    lock();

    void
    unlock();

protected:
    explicit ReadMutex(WritePreferringReadWriteLock & parent_lock);

    WritePreferringReadWriteLock & parent_lock_;

    friend class WritePreferringReadWriteLock;
  };


  class RCLCPP_PUBLIC WriteMutex
  {
public:
    void
    lock();

    void
    unlock();

protected:
    explicit WriteMutex(WritePreferringReadWriteLock & parent_lock);

    WritePreferringReadWriteLock & parent_lock_;

    friend class WritePreferringReadWriteLock;
  };

  RCLCPP_PUBLIC
  ReadMutex &
  get_read_mutex();

  RCLCPP_PUBLIC
  WriteMutex &
  get_write_mutex();

protected:
  bool reader_active_ = false;
  std::size_t number_of_writers_waiting_ = 0;
  bool writer_active_ = false;
  std::mutex mutex_;
  std::condition_variable condition_variable_;
  ReadMutex read_mutex_;
  WriteMutex write_mutex_;
  std::function<void()> enter_waiting_function_;
};

}  // namespace detail
}  // namespace wait_set_policies
}  // namespace rclcpp

#endif  // RCLCPP__WAIT_SET_POLICIES__DETAIL__WRITE_PREFERRING_READ_WRITE_LOCK_HPP_