-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonitor.cc
More file actions
89 lines (70 loc) · 1.39 KB
/
Copy pathmonitor.cc
File metadata and controls
89 lines (70 loc) · 1.39 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
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
#include "monitor.h"
#include <iostream>
#include <condition_variable>
using namespace std;
class Monitor::Impl {
public:
Impl () : mtx_(nullptr), ownedMtx_(new std::mutex()) {
init(ownedMtx_);
}
explicit Impl (std::mutex *m) : mtx_(nullptr), ownedMtx_(nullptr) {
init(m);
}
~Impl() {
cleanup();
}
void lock() {
mtx_->lock();
}
void unlock() {
mtx_->unlock();
}
bool wait(int64_t timeout) {
if (timeout == 0) {
cv_.wait(*lck_);
} else {
if (cv_.wait_for(*lck_, std::chrono::milliseconds(timeout)) == std::cv_status::timeout) {
return false;
}
}
return true;
}
void notify() {
cv_.notify_one();
}
void notifyAll() {
cv_.notify_all();
}
private:
std::mutex *mtx_;
std::mutex *ownedMtx_;
std::unique_lock<std::mutex> *lck_;
std::condition_variable cv_;
void init(std::mutex *m) {
mtx_ = m;
lck_ = new std::unique_lock<std::mutex>(*mtx_, std::defer_lock);
}
void cleanup() {
delete lck_; // must destroy lck_ before ownedMtx_
delete ownedMtx_;
}
};
Monitor::Monitor(std::mutex *m) : impl_(new Impl(m)) {}
Monitor::~Monitor() {
delete impl_;
}
void Monitor::lock() {
impl_->lock();
}
void Monitor::unlock() {
impl_->unlock();
}
bool Monitor::wait(int64_t timeout) {
return impl_->wait(timeout);
}
void Monitor::notify() {
impl_->notify();
}
void Monitor::notifyAll() {
impl_->notifyAll();
}