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