RTC Toolkit  2.0.0
semaphore.hpp
Go to the documentation of this file.
1 
12 #ifndef RTCTK_DATATASK_SEMAPHORE_HPP
13 #define RTCTK_DATATASK_SEMAPHORE_HPP
14 
15 #include <mutex>
16 #include <condition_variable>
17 
18 namespace rtctk::dataTask {
23 class Semaphore {
24 public:
25  Semaphore (int count = 0)
26  : m_count(count)
27  {
28  }
29 
30  inline void Post() { // Signal
31  {
32  std::unique_lock<std::mutex> lock(m_mtx);
33  ++m_count;
34  }
35  m_cv.notify_one();
36  }
37 
38  inline void Wait() { // Wait
39  std::unique_lock<std::mutex> lock(m_mtx);
40  m_cv.wait(lock, [&]{return m_count != 0;});
41  --m_count;
42  }
43 
44  template <class Rep, class Period>
45  inline void Wait(std::chrono::duration<Rep, Period> timeout) {
46  std::unique_lock<std::mutex> lock(m_mtx);
47  auto ret = m_cv.wait_for(lock, timeout, [&]{return m_count != 0;});
48  if(ret == false) {
49  throw(std::runtime_error("Semaphor.Wait() timed out"));
50  }
51  --m_count;
52  }
53 
54  inline bool TryWait() {
55  std::unique_lock<std::mutex> lock(m_mtx);
56  bool ret = false;
57  if(m_count > 0) {
58  --m_count;
59  ret = true;
60  }
61  return ret;
62  }
63 
64  inline void Clear() {
65  std::unique_lock<std::mutex> lock(m_mtx);
66  m_count = 0;
67  }
68 
69 private:
70  int m_count;
71  std::mutex m_mtx;
72  std::condition_variable m_cv;
73 };
74 
75 } // namespace
76 
77 #endif
rtctk::dataTask::Semaphore::Wait
void Wait()
Definition: semaphore.hpp:38
rtctk::dataTask::Semaphore::Wait
void Wait(std::chrono::duration< Rep, Period > timeout)
Definition: semaphore.hpp:45
rtctk::dataTask::Semaphore::Clear
void Clear()
Definition: semaphore.hpp:64
rtctk::dataTask::Semaphore::Semaphore
Semaphore(int count=0)
Definition: semaphore.hpp:25
rtctk::dataTask
Definition: messageQueue.hpp:20
rtctk::dataTask::Semaphore::TryWait
bool TryWait()
Definition: semaphore.hpp:54
rtctk::dataTask::Semaphore::Post
void Post()
Definition: semaphore.hpp:30
rtctk::dataTask::Semaphore
Definition: semaphore.hpp:23