-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReaderWriterLock.h
More file actions
82 lines (61 loc) · 1.85 KB
/
Copy pathReaderWriterLock.h
File metadata and controls
82 lines (61 loc) · 1.85 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
#pragma once
#include <pthread.h>
class ReaderWriterLock {
private:
unsigned int readers; // Number of active readers
public:
pthread_mutex_t read_lock; // Mutex for read access
pthread_mutex_t write_lock; // Mutex for write access
ReaderWriterLock() : readers(0) {
pthread_mutex_init(&read_lock, nullptr);
pthread_mutex_init(&write_lock, nullptr);
}
void readLock() {
pthread_mutex_lock(&read_lock);
readers++;
if (readers == 1) {
pthread_mutex_lock(&write_lock); // First reader locks the write lock
}
pthread_mutex_unlock(&read_lock);
}
void readUnlock() {
pthread_mutex_lock(&read_lock);
readers--;
if (readers == 0) {
pthread_mutex_unlock(&write_lock); // Last reader unlocks the write lock
}
pthread_mutex_unlock(&read_lock);
}
void writeLock() {
pthread_mutex_lock(&write_lock); // Lock for writing
}
void writeUnlock() {
pthread_mutex_unlock(&write_lock); // Unlock for writing
}
~ReaderWriterLock() {
pthread_mutex_destroy(&read_lock);
pthread_mutex_destroy(&write_lock);
}
};
class WithWriteLock {
private:
ReaderWriterLock &rw_lock;
public:
WithWriteLock(ReaderWriterLock &lock) : rw_lock(lock) {
rw_lock.writeLock();
}
~WithWriteLock() {
rw_lock.writeUnlock();
}
};
class WithReadLock {
private:
ReaderWriterLock &rw_lock;
public:
WithReadLock(ReaderWriterLock &lock) : rw_lock(lock) {
rw_lock.readLock();
}
~WithReadLock() {
rw_lock.readUnlock();
}
};