Semaphore.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. // Copyright 2016 Esteve Fernandez <esteve@apache.org>
  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. #ifndef FASTRTPS_SEMAPHORE_H_
  15. #define FASTRTPS_SEMAPHORE_H_
  16. #include <condition_variable>
  17. #include <mutex>
  18. namespace eprosima {
  19. namespace fastrtps {
  20. class Semaphore {
  21. public:
  22. explicit Semaphore(size_t count = 0);
  23. Semaphore(const Semaphore&) = delete;
  24. Semaphore& operator=(const Semaphore&) = delete;
  25. void post();
  26. void wait();
  27. void disable();
  28. void enable();
  29. void post(int n);
  30. private:
  31. size_t count_;
  32. std::mutex mutex_;
  33. std::condition_variable cv_;
  34. bool disable_;
  35. };
  36. inline Semaphore::Semaphore(size_t count) : count_(count), disable_(false) {}
  37. inline void Semaphore::post() {
  38. std::lock_guard<std::mutex> lock(mutex_);
  39. if (!disable_)
  40. {
  41. ++count_;
  42. cv_.notify_one();
  43. }
  44. }
  45. inline void Semaphore::post(int n) {
  46. std::lock_guard<std::mutex> lock(mutex_);
  47. if (!disable_)
  48. {
  49. count_ += n;
  50. for (int i = 0; i < n; ++i)
  51. {
  52. cv_.notify_one();
  53. }
  54. }
  55. }
  56. inline void Semaphore::disable() {
  57. std::lock_guard<std::mutex> lock(mutex_);
  58. if (!disable_)
  59. {
  60. count_ = (size_t)-1L;
  61. cv_.notify_all();
  62. disable_ = true;
  63. }
  64. }
  65. inline void Semaphore::enable() {
  66. std::lock_guard<std::mutex> lock(mutex_);
  67. if (disable_)
  68. {
  69. count_ = 0;
  70. disable_ = false;
  71. }
  72. }
  73. inline void Semaphore::wait() {
  74. std::unique_lock<std::mutex> lock(mutex_);
  75. if (!disable_)
  76. {
  77. cv_.wait(lock, [&] {
  78. if (disable_) return true;
  79. return count_ > 0;
  80. });
  81. --count_;
  82. }
  83. }
  84. } // fastrtps
  85. } // eprosima
  86. #endif // FASTRTPS_SEMAPHORE_H_