-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathEvent20.hpp
88 lines (71 loc) · 2.38 KB
/
Event20.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#ifndef EVENT20_HPP
#define EVENT20_HPP
// std library
#include <chrono>
#include <vector>
#include <thread>
// Application
#include "Monitor.hpp"
namespace utils
{
class Event final
{
using threads_ids_type = std::vector<std::thread::id>;
public:
explicit Event(bool autoReset) noexcept
: autoReset_{autoReset}
{}
~Event() = default;
// Copy functions forbidden
Event(const Event&) = delete;
Event& operator=(const Event&) = delete;
// Move operations forbidden
Event(Event&&) = delete;
Event& operator=(Event&&) = delete;
inline void wait() noexcept
{
{
auto lock = sync_.getLock();
if (flag_) return; // premature signalization
waitingThreads_.push_back(std::this_thread::get_id());
}
auto lock = sync_.wait([this] { return flag_; });
update_waiting_threads(waitingThreads_);
if (autoReset_ && waitingThreads_.empty()) flag_ = false;
}
inline bool wait_for(std::chrono::milliseconds timeout) noexcept
{
{
auto lock = sync_.getLock();
if (flag_) return true; // premature signalization
waitingThreads_.push_back(std::this_thread::get_id());
}
auto [result, lock] = sync_.wait_for(timeout, [this] { return flag_; });
update_waiting_threads(waitingThreads_);
if (autoReset_ && waitingThreads_.empty())
flag_ = false; // for broadcast to work with auto reset flag set to true
return result;
}
inline void signal() noexcept
{
sync_.notify_one([this] { flag_ = true; });
}
inline void broadcast() noexcept
{
sync_.notify_all([this] { flag_ = true; });
}
private:
inline void update_waiting_threads(threads_ids_type& waitingThreads) noexcept
{
waitingThreads_.erase(
std::remove(waitingThreads.begin(), waitingThreads.end(), std::this_thread::get_id()),
waitingThreads.end());
}
private:
Monitor<> sync_{};
const bool autoReset_;
bool flag_{false};
threads_ids_type waitingThreads_;
};
} // namespace utils
#endif // EVENT20_HPP