12#include <condition_variable>
30 std::condition_variable cv;
32 int active_readers = 0;
33 int waiting_writers = 0;
34 bool writer_active =
false;
44 std::unique_lock<std::mutex> lock(mtx);
47 while(writer_active || waiting_writers > 0) {
60 std::unique_lock<std::mutex> lock(mtx);
63 if(active_readers == 0)
73 std::unique_lock<std::mutex> lock(mtx);
77 while(active_readers > 0 || writer_active) {
90 std::unique_lock<std::mutex> lock(mtx);
91 writer_active =
false;
104 std::lock_guard<std::mutex> log_lock(
log_mtx);
105 std::cout <<
"[Reader " <<
id <<
"] Start Reading..." << std::endl;
108 std::this_thread::sleep_for(std::chrono::milliseconds(200));
111 std::lock_guard<std::mutex> log_lock(
log_mtx);
112 std::cout <<
"[Reader " <<
id <<
"] Finished Reading." << std::endl;
123 std::this_thread::sleep_for(std::chrono::milliseconds(50));
127 std::lock_guard<std::mutex> log_lock(
log_mtx);
128 std::cout <<
">>> [Writer " <<
id <<
"] EXCLUSIVE WRITE START <<<" << std::endl;
131 std::this_thread::sleep_for(std::chrono::milliseconds(500));
134 std::lock_guard<std::mutex> log_lock(
log_mtx);
135 std::cout <<
">>> [Writer " <<
id <<
"] EXCLUSIVE WRITE END <<<" << std::endl;
146 std::vector<std::thread> threads;
148 for(
int i=1; i<=50; i++) {
152 std::this_thread::sleep_for(std::chrono::milliseconds(2000));
154 for(
int i=1; i<=2; i++) {
158 std::this_thread::sleep_for(std::chrono::milliseconds(2000));
160 for(
int i=1001; i<=1100; i++) {
164 for(
auto& t : threads) {
169 std::cout <<
"All metadata operations completed." << std::endl;
std::mutex log_mtx
Global mutex to prevent console output interleaving. Standard output is not thread-safe; this ensures...
void readerTask(RWLock *rw, int id)
Simulates a reader's lifecycle.
int main(void)
Entry point for the custom RWLock demonstration. Creates a mix of reader and writer threads to demons...
void writerTask(RWLock *rw, int id)
Simulates a writer's lifecycle.
A custom synchronization primitive for the Readers-Writers problem.
void unlock_read()
Releases the shared read lock.
void lock_write()
Acquires an exclusive write lock.
void unlock_write()
Releases the exclusive write lock.
void lock_read()
Acquires a shared read lock.