Dev Essential
Loading...
Searching...
No Matches
semaphore_impl.h
Go to the documentation of this file.
1
14
15#ifndef A_UTIL_UTIL_CONCURRENCY_DETAIL_SEMAPHORE_IMPL_HEADER_INCLUDED
16#define A_UTIL_UTIL_CONCURRENCY_DETAIL_SEMAPHORE_IMPL_HEADER_INCLUDED
17
20
21#ifndef _MSC_VER
22#include <condition_variable>
23#include <thread>
24#else
25#include <mutex>
26#endif // !_MSC_VER
27
28#include <stdexcept>
29
30namespace a_util {
31namespace concurrency {
32namespace detail {
33template <typename Mutex, typename CondVar>
34inline basic_semaphore<Mutex, CondVar>::basic_semaphore(int count)
35 : _mutex(), _cv(), _lock_count(count)
36{
37}
38
39template <typename Mutex, typename CondVar>
41{
42 std::unique_lock<Mutex> lock(_mutex);
44 _cv.notify_all();
45}
47template <typename Mutex, typename CondVar>
49{
50 std::unique_lock<Mutex> lock(_mutex);
51
52 _cv.wait(lock, [&]() { return _lock_count > 0; });
53
54 --_lock_count;
55}
56
57template <typename Mutex, typename CondVar>
59{
60 std::unique_lock<Mutex> lock(_mutex);
61
62 if (_lock_count > 0) {
64 return true;
65 }
66 else {
67 return false;
68 }
69}
70
71template <typename Mutex, typename CondVar>
73{
74 std::unique_lock<Mutex> lock(_mutex);
75 _lock_count = 0;
76}
77
78template <typename Mutex, typename CondVar>
80{
81 std::unique_lock<Mutex> lock(_mutex);
82 return _lock_count > 0;
83}
84
85template <typename Mutex, typename CondVar>
86template <typename Rep, typename Period>
88 const std::chrono::duration<Rep, Period>& timeout)
89{
90 if (timeout.count() < 0) {
91 throw std::invalid_argument("timeout.count() < 0");
92 }
93
94 std::unique_lock<Mutex> lock(_mutex);
95 if (!_cv.wait_for(lock, timeout, [&]() { return _lock_count > 0; })) {
96 return false;
97 }
98 else {
100 return true;
101 }
102}
103
104} // namespace detail
105} // namespace concurrency
106} // namespace a_util
107
108#endif // A_UTIL_UTIL_CONCURRENCY_DETAIL_SEMAPHORE_IMPL_HEADER_INCLUDED
void wait()
Decrement the counter, blocks until the count becomes non-zero (if neccessary)
Definition semaphore_impl.h:48
void notify()
Increment the counter and notify any waiters.
Definition semaphore_impl.h:40
bool is_set()
Definition semaphore_impl.h:79
Mutex _mutex
The mutex to handle.
Definition semaphore_decl.h:75
void reset()
Reset the counter to 0.
Definition semaphore_impl.h:72
bool try_wait()
Definition semaphore_impl.h:58
int _lock_count
The lock count.
Definition semaphore_decl.h:77
CondVar _cv
The condition variable used to handle the notifications.
Definition semaphore_decl.h:76
bool wait_for(const std::chrono::duration< Rep, Period > &timeout)
Definition semaphore_impl.h:87
Serves as namespace for concurrency implementation details.
Definition concurrency.h:33
Definition concurrency.h:24
Serves as the root component, with common functionality documented in core functionality.
Definition base.h:24