libpromeki 1.0.0-alpha
PROfessional MEdia toolKIt
 
Loading...
Searching...
No Matches
waitcondition.h
Go to the documentation of this file.
1
8#pragma once
9
10
11#include <promeki/config.h>
12#if PROMEKI_ENABLE_CORE
13#include <chrono>
14#include <type_traits>
15#include <condition_variable>
16#include <promeki/namespace.h>
17#include <promeki/error.h>
18#include <promeki/mutex.h>
19
20PROMEKI_NAMESPACE_BEGIN
21
34class WaitCondition {
35 public:
37 WaitCondition() = default;
38
40 ~WaitCondition() = default;
41
42 WaitCondition(const WaitCondition &) = delete;
43 WaitCondition &operator=(const WaitCondition &) = delete;
44 WaitCondition(WaitCondition &&) = delete;
45 WaitCondition &operator=(WaitCondition &&) = delete;
46
58 Error wait(Mutex &mutex, unsigned int timeoutMs = 0) {
59 std::unique_lock<std::mutex> lock(mutex._mutex, std::adopt_lock);
60 if (timeoutMs == 0) {
61 _cv.wait(lock);
62 lock.release();
63 return Error::Ok;
64 }
65 std::cv_status status = _cv.wait_for(lock, std::chrono::milliseconds(timeoutMs));
66 lock.release();
67 return status == std::cv_status::no_timeout ? Error::Ok : Error::Timeout;
68 }
69
84 template <typename Predicate, typename = std::enable_if_t<std::is_invocable_r_v<bool, Predicate>>>
85 Error wait(Mutex &mutex, Predicate pred, unsigned int timeoutMs = 0) {
86 std::unique_lock<std::mutex> lock(mutex._mutex, std::adopt_lock);
87 if (timeoutMs == 0) {
88 _cv.wait(lock, pred);
89 lock.release();
90 return Error::Ok;
91 }
92 bool result = _cv.wait_for(lock, std::chrono::milliseconds(timeoutMs), pred);
93 lock.release();
94 return result ? Error::Ok : Error::Timeout;
95 }
96
98 void wakeOne() { _cv.notify_one(); }
99
101 void wakeAll() { _cv.notify_all(); }
102
103 private:
104 std::condition_variable _cv;
105};
106
107PROMEKI_NAMESPACE_END
108
109#endif // PROMEKI_ENABLE_CORE