A custom synchronization primitive for the Readers-Writers problem.
More...
A custom synchronization primitive for the Readers-Writers problem.
- This class uses a single std::mutex and std::condition_variable to manage state. It implements a "Writer Preference" policy.
Definition at line 27 of file CustomRWLock.cpp.
◆ lock_read()
| void RWLock::lock_read |
( |
| ) |
|
|
inline |
Acquires a shared read lock.
- A writer is currently active.
- There are writers waiting in the queue (Starvation Protection).
Definition at line 43 of file CustomRWLock.cpp.
43 {
44 std::unique_lock<std::mutex> lock(mtx);
45
46
47 while(writer_active || waiting_writers > 0) {
48 cv.wait(lock);
49 }
50
51 active_readers++;
52 }
Referenced by readerTask().
◆ lock_write()
| void RWLock::lock_write |
( |
| ) |
|
|
inline |
Acquires an exclusive write lock.
- Increments the waiting_writers count to block new readers. Blocks until all active readers and any active writer have finished.
Definition at line 72 of file CustomRWLock.cpp.
72 {
73 std::unique_lock<std::mutex> lock(mtx);
74 waiting_writers++;
75
76
77 while(active_readers > 0 || writer_active) {
78 cv.wait(lock);
79 }
80
81 waiting_writers--;
82 writer_active = true;
83 }
Referenced by writerTask().
◆ unlock_read()
| void RWLock::unlock_read |
( |
| ) |
|
|
inline |
Releases the shared read lock.
- If this was the last active reader, it notifies all waiting threads (potentially waking a waiting writer).
Definition at line 59 of file CustomRWLock.cpp.
59 {
60 std::unique_lock<std::mutex> lock(mtx);
61 active_readers--;
62
63 if(active_readers == 0)
64 cv.notify_all();
65 }
Referenced by readerTask().
◆ unlock_write()
| void RWLock::unlock_write |
( |
| ) |
|
|
inline |
Releases the exclusive write lock.
- Sets writer_active to false and wakes all waiting threads.
Definition at line 89 of file CustomRWLock.cpp.
89 {
90 std::unique_lock<std::mutex> lock(mtx);
91 writer_active = false;
92 cv.notify_all();
93 }
Referenced by writerTask().
The documentation for this class was generated from the following file: