C++ Concurrency Sandbox
Loading...
Searching...
No Matches
RWLock Class Reference

A custom synchronization primitive for the Readers-Writers problem. More...

Collaboration diagram for RWLock:

Public Member Functions

void lock_read ()
 Acquires a shared read lock.
 
void unlock_read ()
 Releases the shared read lock.
 
void lock_write ()
 Acquires an exclusive write lock.
 
void unlock_write ()
 Releases the exclusive write lock.
 

Detailed Description

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.

Member Function Documentation

◆ lock_read()

void RWLock::lock_read ( )
inline

Acquires a shared read lock.

  • Blocks if:
  1. A writer is currently active.
  2. 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 // Wait while a writer is active OR a writer is waiting
47 while(writer_active || waiting_writers > 0) {
48 cv.wait(lock);
49 }
50
51 active_readers++;
52 }

Referenced by readerTask().

Here is the caller graph for this function:

◆ 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 // Wait while any readers or writers are active
77 while(active_readers > 0 || writer_active) {
78 cv.wait(lock);
79 }
80
81 waiting_writers--;
82 writer_active = true;
83 }

Referenced by writerTask().

Here is the caller graph for this function:

◆ 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().

Here is the caller graph for this function:

◆ 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().

Here is the caller graph for this function:

The documentation for this class was generated from the following file: