|
1
|
1 #pragma once
|
|
|
2
|
|
|
3 // Alternate lightweight implementation of pfc::event, with similar method sigantures but no support for multi-event-wait-for-any.
|
|
|
4 // It's a safe drop-in replacement for the regular event - code trying to use unsupported methods will fail to compile rather than behave incorrectly.
|
|
|
5
|
|
|
6 // Rationale:
|
|
|
7 // Mac/Linux multi-wait-capable pipe-backed event is relatively expensive, in terms of CPU, memory and file descriptors opened.
|
|
|
8 // On Windows, event_std still outperforms regular win32 event but the difference is mostly insignificant in real life use cases.
|
|
|
9
|
|
|
10 #include <mutex>
|
|
|
11 #include <condition_variable>
|
|
|
12 namespace pfc {
|
|
|
13 class event_std {
|
|
|
14 public:
|
|
|
15 void set_state(bool v = true) {
|
|
|
16 std::scoped_lock lock(m_mutex);
|
|
|
17 if (m_state != v) {
|
|
|
18 m_state = v;
|
|
|
19 if (v) m_condition.notify_all();
|
|
|
20 }
|
|
|
21 }
|
|
|
22 bool is_set() const { return m_state; }
|
|
|
23 void wait() {
|
|
|
24 std::unique_lock lock(m_mutex);
|
|
|
25 m_condition.wait(lock, [this] { return this->m_state; });
|
|
|
26 }
|
|
|
27 bool wait_for(double timeout) {
|
|
|
28 if (timeout < 0) { wait(); return true; }
|
|
|
29 std::unique_lock lock(m_mutex);
|
|
|
30 return m_condition.wait_for(lock, std::chrono::duration<double>(timeout), [this] { return this->m_state; });
|
|
|
31 }
|
|
|
32 void wait_and_clear() {
|
|
|
33 std::unique_lock lock(m_mutex);
|
|
|
34 m_condition.wait(lock, [this] { return this->m_state; });
|
|
|
35 m_state = false;
|
|
|
36 }
|
|
|
37 bool wait_for_and_clear(double timeout) {
|
|
|
38 if ( timeout < 0 ) {wait_and_clear(); return true;}
|
|
|
39 std::unique_lock lock(m_mutex);
|
|
|
40 bool rv = m_condition.wait_for(lock, std::chrono::duration<double>(timeout), [this] { return this->m_state; });
|
|
|
41 if ( rv ) m_state = false;
|
|
|
42 return rv;
|
|
|
43 }
|
|
|
44 private:
|
|
|
45 volatile bool m_state = false;
|
|
|
46 std::condition_variable m_condition;
|
|
|
47 std::mutex m_mutex;
|
|
|
48 };
|
|
|
49 }
|