123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- #ifndef FASTRTPS_SEMAPHORE_H_
- #define FASTRTPS_SEMAPHORE_H_
- #include <condition_variable>
- #include <mutex>
- namespace eprosima {
- namespace fastrtps {
- class Semaphore {
- public:
- explicit Semaphore(size_t count = 0);
- Semaphore(const Semaphore&) = delete;
- Semaphore& operator=(const Semaphore&) = delete;
- void post();
- void wait();
- void disable();
- void enable();
- void post(int n);
- private:
- size_t count_;
- std::mutex mutex_;
- std::condition_variable cv_;
- bool disable_;
- };
- inline Semaphore::Semaphore(size_t count) : count_(count), disable_(false) {}
- inline void Semaphore::post() {
- std::lock_guard<std::mutex> lock(mutex_);
- if (!disable_)
- {
- ++count_;
- cv_.notify_one();
- }
- }
- inline void Semaphore::post(int n) {
- std::lock_guard<std::mutex> lock(mutex_);
- if (!disable_)
- {
- count_ += n;
- for (int i = 0; i < n; ++i)
- {
- cv_.notify_one();
- }
- }
- }
- inline void Semaphore::disable() {
- std::lock_guard<std::mutex> lock(mutex_);
- if (!disable_)
- {
- count_ = (size_t)-1L;
- cv_.notify_all();
- disable_ = true;
- }
- }
- inline void Semaphore::enable() {
- std::lock_guard<std::mutex> lock(mutex_);
- if (disable_)
- {
- count_ = 0;
- disable_ = false;
- }
- }
- inline void Semaphore::wait() {
- std::unique_lock<std::mutex> lock(mutex_);
- if (!disable_)
- {
- cv_.wait(lock, [&] {
- if (disable_) return true;
- return count_ > 0;
- });
- --count_;
- }
- }
- }
- }
- #endif
|