-
Notifications
You must be signed in to change notification settings - Fork 0
/
rwlock.hpp
97 lines (79 loc) · 2.3 KB
/
rwlock.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
89
90
91
92
93
94
95
96
97
#include <mutex>
#include <condition_variable>
class rwlock {
public:
rwlock() = default;
~rwlock() = default;
public:
void lock_read() {
//std::cout << "lock read" << std::endl;
std::unique_lock<std::mutex> ulk(counter_mutex);
cond_r.wait(ulk, [=]() -> bool { return write_cnt == 0; });
++read_cnt;
}
void lock_write() {
//std::cout << "lock write" << std::endl;
std::unique_lock<std::mutex> ulk(counter_mutex);
++write_cnt;
cond_w.wait(ulk, [=]() -> bool { return read_cnt == 0 && !inwriteflag; });
inwriteflag = true;
}
void release_read() {
//std::cout << "release read" << std::endl;
std::unique_lock<std::mutex> ulk(counter_mutex);
if (--read_cnt == 0 && write_cnt > 0) {
cond_w.notify_one();
}
}
void release_write() {
//std::cout << "release write" << std::endl;
std::unique_lock<std::mutex> ulk(counter_mutex);
if (--write_cnt == 0) {
cond_r.notify_all();
} else {
cond_w.notify_one();
}
inwriteflag = false;
}
private:
volatile size_t read_cnt{0};
volatile size_t write_cnt{0};
volatile bool inwriteflag{false};
std::mutex counter_mutex;
std::condition_variable cond_w;
std::condition_variable cond_r;
};
template<typename _RWLockable>
class unique_writeguard {
public:
explicit unique_writeguard(_RWLockable &rw_lockable)
: rw_lockable_(rw_lockable) {
rw_lockable_.lock_write();
}
~unique_writeguard() {
rw_lockable_.release_write();
}
private:
unique_writeguard() = delete;
unique_writeguard(const unique_writeguard &) = delete;
unique_writeguard &operator=(const unique_writeguard &) = delete;
private:
_RWLockable &rw_lockable_;
};
template<typename _RWLockable>
class unique_readguard {
public:
explicit unique_readguard(_RWLockable &rw_lockable)
: rw_lockable_(rw_lockable) {
rw_lockable_.lock_read();
}
~unique_readguard() {
rw_lockable_.release_read();
}
private:
unique_readguard() = delete;
unique_readguard(const unique_readguard &) = delete;
unique_readguard &operator=(const unique_readguard &) = delete;
private:
_RWLockable &rw_lockable_;
};