Reader-Writer problem using Monitors (pthreads)
Prerequisite – Monitors, Readers-Writers Problem
There is a shared resource which is accessed by multiple processes i.e. readers and writers. Any number of readers can read from the shared resource simultaneously, but only one writer can write to the shared resource at a time. When a writer is writing data to the resource, no other process can access the resource. A writer cannot write to the resource if there are any readers accessing the resource at that time. Similarly, a reader can not read if there is a writer accessing the resource or if there are any waiting writers.
The Reader-Writer problem using monitor can be implemented using pthreads. The POSIX threads (or pthread) libraries are a standards based thread API for C/C++. The library provides following synchronization mechanisms:
- Mutexes (pthread_mutex_t) – Mutual exclusion lock:
Block access to variables by other threads. This enforces exclusive access by a thread to a variable or set of variables.
- Condition Variables – (pthread_cond_t):
The condition variable mechanism allows threads to suspend execution and relinquish the processor until some condition is true.
Implementation of Reader-Writer solution using pthread library:
Execute the program using following command in your Linux system
$g++ -pthread program_name.cpp $./a.out or $g++ -pthread program_name.cpp -o object_name $./object_name
Attention reader! Don’t stop learning now. Get hold of all the important CS Theory concepts for SDE interviews with the CS Theory Course at a student-friendly price and become industry ready.