-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevent_variable.h
More file actions
62 lines (46 loc) · 1.18 KB
/
Copy pathevent_variable.h
File metadata and controls
62 lines (46 loc) · 1.18 KB
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
/*
* Event variable implements in C++11.
*
* file: event_variable.h
* date: 2016-01-03
* author: chenhaotian93@gmail.com
*/
#include <atomic>
#include <condition_variable>
#include <chrono>
#include <functional>
#include <mutex>
#include <ratio>
class EventVariable {
public:
explicit EventVariable(): m_is_set(false) {}
void clear() { m_is_set = false; }
bool is_set() const { return m_is_set; }
// Notify all waiters.
void set() {
m_is_set = true;
m_condition.notify_all();
}
// Wait synchronized.
void wait() {
if (m_is_set) {
return;
}
std::unique_lock<std::mutex> lock(m_mutex);
m_condition.wait(lock);
}
// Wait with timeout.
template<class Rep, class Period>
bool wait_for(const std::chrono::duration<Rep, Period>& timeout) {
if (m_is_set) {
return true;
}
std::unique_lock<std::mutex> lock(m_mutex);
return std::cv_status::no_timeout ==
m_condition.wait_for(lock, timeout);
}
private:
std::atomic<bool> m_is_set;
std::mutex m_mutex;
std::condition_variable m_condition;
};