Reader-Writer problem using Monitors (pthreads) Last Updated : 07 Feb, 2022 Comments Improve Suggest changes Like Article Like Report Prerequisite - Monitors, Readers-Writers Problem There is a shared resource that 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 a monitor can be implemented using pthreads. The POSIX threads (or pthread) libraries are a standards-based thread API for C/C++. The library provides the 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 the following command in your Linux system $g++ -pthread program_name.cpp $./a.out or $g++ -pthread program_name.cpp -o object_name $./object_name Code: CPP // Reader-Writer problem using monitors #include <iostream> #include <pthread.h> #include <unistd.h> using namespace std; class monitor { private: // no. of readers int rcnt; // no. of writers int wcnt; // no. of readers waiting int waitr; // no. of writers waiting int waitw; // condition variable to check whether reader can read pthread_cond_t canread; // condition variable to check whether writer can write pthread_cond_t canwrite; // mutex for synchronization pthread_mutex_t condlock; public: monitor() { rcnt = 0; wcnt = 0; waitr = 0; waitw = 0; pthread_cond_init(&canread, NULL); pthread_cond_init(&canwrite, NULL); pthread_mutex_init(&condlock, NULL); } // mutex provide synchronization so that no other thread // can change the value of data void beginread(int i) { pthread_mutex_lock(&condlock); // if there are active or waiting writers if (wcnt == 1 || waitw > 0) { // incrementing waiting readers waitr++; // reader suspended pthread_cond_wait(&canread, &condlock); waitr--; } // else reader reads the resource rcnt++; cout << "reader " << i << " is reading\n"; pthread_mutex_unlock(&condlock); pthread_cond_broadcast(&canread); } void endread(int i) { // if there are no readers left then writer enters monitor pthread_mutex_lock(&condlock); if (--rcnt == 0) pthread_cond_signal(&canwrite); pthread_mutex_unlock(&condlock); } void beginwrite(int i) { pthread_mutex_lock(&condlock); // a writer can enter when there are no active // or waiting readers or other writer if (wcnt == 1 || rcnt > 0) { ++waitw; pthread_cond_wait(&canwrite, &condlock); --waitw; } wcnt = 1; cout << "writer " << i << " is writing\n"; pthread_mutex_unlock(&condlock); } void endwrite(int i) { pthread_mutex_lock(&condlock); wcnt = 0; // if any readers are waiting, threads are unblocked if (waitr > 0) pthread_cond_signal(&canread); else pthread_cond_signal(&canwrite); pthread_mutex_unlock(&condlock); } } // global object of monitor class M; void* reader(void* id) { int c = 0; int i = *(int*)id; // each reader attempts to read 5 times while (c < 5) { usleep(1); M.beginread(i); M.endread(i); c++; } } void* writer(void* id) { int c = 0; int i = *(int*)id; // each writer attempts to write 5 times while (c < 5) { usleep(1); M.beginwrite(i); M.endwrite(i); c++; } } int main() { pthread_t r[5], w[5]; int id[5]; for (int i = 0; i < 5; i++) { id[i] = i; // creating threads which execute reader function pthread_create(&r[i], NULL, &reader, &id[i]); // creating threads which execute writer function pthread_create(&w[i], NULL, &writer, &id[i]); } for (int i = 0; i < 5; i++) { pthread_join(r[i], NULL); } for (int i = 0; i < 5; i++) { pthread_join(w[i], NULL); } } Output: Comment More infoAdvertise with us Next Article Reader-Writer problem using Monitors (pthreads) P PrachiHooda Follow Improve Article Tags : Operating Systems Process Synchronization Similar Reads Operating System Tutorial An Operating System(OS) is a software that manages and handles hardware and software resources of a computing device. Responsible for managing and controlling all the activities and sharing of computer resources among different running applications.A low-level Software that includes all the basic fu 4 min read Types of Operating Systems Operating Systems can be categorized according to different criteria like whether an operating system is for mobile devices (examples Android and iOS) or desktop (examples Windows and Linux). Here, we are going to classify based on functionalities an operating system provides.8 Main Operating System 11 min read CPU Scheduling in Operating Systems CPU scheduling is a process used by the operating system to decide which task or process gets to use the CPU at a particular time. This is important because a CPU can only handle one task at a time, but there are usually many tasks that need to be processed. The following are different purposes of a 8 min read Introduction of Deadlock in Operating System A deadlock is a situation where a set of processes is blocked because each process is holding a resource and waiting for another resource acquired by some other process. In this article, we will discuss deadlock, its necessary conditions, etc. in detail.Deadlock is a situation in computing where two 11 min read What is an Operating System? An Operating System is a System software that manages all the resources of the computing device. Acts as an interface between the software and different parts of the computer or the computer hardware. Manages the overall resources and operations of the computer. Controls and monitors the execution o 9 min read Page Replacement Algorithms in Operating Systems In an operating system that uses paging for memory management, a page replacement algorithm is needed to decide which page needs to be replaced when a new page comes in. Page replacement becomes necessary when a page fault occurs and no free page frames are in memory. in this article, we will discus 7 min read Paging in Operating System Paging is the process of moving parts of a program, called pages, from secondary storage (like a hard drive) into the main memory (RAM). The main idea behind paging is to break a program into smaller fixed-size blocks called pages.To keep track of where each page is stored in memory, the operating s 8 min read Disk Scheduling Algorithms Disk scheduling algorithms are crucial in managing how data is read from and written to a computer's hard disk. These algorithms help determine the order in which disk read and write requests are processed, significantly impacting the speed and efficiency of data access. Common disk scheduling metho 12 min read Banker's Algorithm in Operating System Banker's Algorithm is a resource allocation and deadlock avoidance algorithm used in operating systems. It ensures that a system remains in a safe state by carefully allocating resources to processes while avoiding unsafe states that could lead to deadlocks.The Banker's Algorithm is a smart way for 8 min read Memory Management in Operating System The term memory can be defined as a collection of data in a specific format. It is used to store instructions and process data. The memory comprises a large array or group of words or bytes, each with its own location. The primary purpose of a computer system is to execute programs. These programs, 10 min read Like