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