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