-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathRWLock.h
50 lines (42 loc) · 926 Bytes
/
RWLock.h
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
#pragma once
#include <mutex>
using namespace std;
class RWLock {
mutex m_mutex; // re-entrance not allowed
condition_variable m_readingAllowed, m_writingAllowed;
bool m_writeLocked = false; // locked for writing
size_t m_readLocked = 0; // number of concurrent readers
public:
size_t getReaders() const {
return m_readLocked;
}
void lockR() {
unique_lock<mutex> monitor(m_mutex);
while (m_writeLocked)
{
m_readingAllowed.wait(monitor);
}
m_readLocked++;
}
void unlockR() {
unique_lock<mutex> monitor(m_mutex);
m_readLocked--;
if (m_readLocked == 0)
{
m_writingAllowed.notify_all();
}
}
void lockW() {
unique_lock<mutex> monitor(m_mutex);
while (m_writeLocked && m_readLocked != 0)
{
m_writingAllowed.wait(monitor);
}
m_writeLocked = true;
}
void unlockW() {
unique_lock<mutex> monitor(m_mutex);
m_writeLocked = false;
m_readingAllowed.notify_all();
}
};