The Wayback Machine - https://web.archive.org/web/20241001022959/https://www.geeksforgeeks.org/reader-writers-solution-using-monitors/
Open In App

Reader-Writers solution using Monitors

Last Updated : 05 May, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite – Process Synchronization, Monitors, Readers-Writers Problem Considering a shared Database our objectives are:

  • Readers can access database only when there are no writers.
  • Writers can access database only when there are no readers or writers.
  • Only one thread can manipulate the state variables at a time.

What is the Reader-Writers problem?
The Reader-Writers problem is a classical synchronization problem in computer science, where multiple threads (readers and writers) need to access a shared resource (e.g., a database) in a mutually exclusive way, while avoiding conflicts and ensuring correctness.

How does the Reader-Writers solution using Monitors ensure fairness?
The Reader-Writers solution using Monitors ensures a kind of back-and-forth form of fairness, where once a reader is waiting, readers will get in next, and if a writer is waiting, one writer will get in next. This is mostly fair, although once it lets a reader in, it lets all waiting readers in all at once, even if some showed up “after” other waiting writers. In the “EndWrite” code (it signals CanWrite without checking for waiting writers), in the EndRead code (same thing), and in StartRead (signals CanRead at the end).

Basic structure of a solution –

Reader()
   Wait until no writers
   Access database
   Check out – wake up a waiting writer
Writer()
   Wait until no active readers or writers
   Access database
   Check out – wake up waiting readers or writer

–Now let’s suppose that a writer is active and a mixture of readers and writers now show up. Who should get in next? –Or suppose that a writer is waiting and an endless of stream of readers keep showing up. Would it be fair for them to become active? So we’ll implement a kind of back-and-forth form of fairness:

  • Once a reader is waiting, readers will get in next.
  • If a writer is waiting, one writer will get in next.

Implementation of the solution using monitors:-

  1. The methods should be executed with mutual exclusion i.e. At each point in time, at most one thread may be executing any of its methods.
  2. Monitors also provide a mechanism for threads to temporarily give up exclusive access, in order to wait for some condition to be met, before regaining exclusive access and resuming their task.
  3. Monitors also have a mechanism for signaling other threads that such conditions have been met.
  4. So in this implementation only mutual exclusion is not enough. Threads attempting an operation may need to wait until some assertion P holds true.
  5. While a thread is waiting upon a condition variable, that thread is not considered to occupy the monitor, and so other threads may enter the monitor to change the monitor’s state.

Code – 

C




// STATE VARIABLES
// Number of active readers; initially = 0
int NReaders = 0;
 
// Number of waiting readers; initially = 0
int WaitingReaders = 0;
 
// Number of active writers; initially = 0
int NWriters = 0;
 
// Number of waiting writers; initially = 0
int WaitingWriters = 0;
 
Condition canRead = NULL;
Condition canWrite = NULL;
 
Void BeginWrite()
{
 
    // A writer can enter if there are no other
    // active writers and no readers are waiting
    if (NWriters == 1 || NReaders > 0) {
 
        ++WaitingWriters;
        wait(CanWrite);
        --WaitingWriters;
    }
 
    NWriters = 1;
}
 
Void EndWrite()
{
 
    NWriters = 0;
 
    // Checks to see if any readers are waiting
    if (WaitingReaders)
 
        Signal(CanRead);
 
    else
 
        Signal(CanWrite);
}
 
Void BeginRead()
{
 
    // A reader can enter if there are no writers
    // active or waiting, so we can have
    // many readers active all at once
    if (NWriters == 1 || WaitingWriters > 0) {
 
        ++WaitingReaders;
 
        // Otherwise, a reader waits (maybe many do)
        Wait(CanRead);
 
        --WaitingReaders;
    }
 
    ++NReaders;
    Signal(CanRead);
}
 
Void EndRead()
{
 
    // When a reader finishes, if it was the last reader,
    // it lets a writer in (if any is there).
    if (--NReaders == 0)
 
        Signal(CanWrite);
}


Understanding the solution:-

  1. If a writer is waiting, readers queue up.
  2. If a reader (or another writer) is active or waiting, writers queue up.
  3. This is mostly fair, although once it lets a reader in, it lets ALL waiting readers in all at once, even if some showed up “after” other waiting writers.
  4. In the “EndWrite” code (it signals CanWrite without checking for waiting writers)
  5. In the EndRead code (same thing)
  6. In StartRead (signals CanRead at the end)

With Semaphores we never did have a “fair” solution of this sort. In fact it can be done but the code is quite tricky. Here the straightforward solution works in the desired way! Monitors are less error-prone and also easier to understand.



Similar Reads

Readers-Writers Problem | Writers Preference Solution
Prerequisites — Readers-Writers Problem | Set 1 (Introduction and Readers Preference Solution), Semaphores in Process Synchronization In Process-synchronization, there is a very classical synchronization problem named as Readers-writers problem. The problem has several sub-problems or variations all involving priorities, one of which is discussed i
4 min read
Reader-Writer problem using Monitors (pthreads)
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 acces
4 min read
Dining-Philosophers Solution Using Monitors
Prerequisite: Monitor, Process Synchronization Dining-Philosophers Problem - N philosophers seated around a circular table There is one chopstick between each philosopherA philosopher must pick up its two nearest chopsticks in order to eatA philosopher must pick up first one chopstick, then the second one, not both at once We need an algorithm for
4 min read
Readers-Writers Problem | Set 1 (Introduction and Readers Preference Solution)
The readers-writer problem in operating systems is about managing access to shared data. It allows multiple readers to read data at the same time without issues but ensures that only one writer can write at a time, and no one can read while writing is happening. This helps prevent data corruption and ensures smooth operation in multi-user systems.
8 min read
Monitors in Process Synchronization
Monitors are a higher-level synchronization construct that simplifies process synchronization by providing a high-level abstraction for data access and synchronization. Monitors are implemented as programming language constructs, typically in object-oriented languages, and provide mutual exclusion, condition variables, and data encapsulation in a s
3 min read
Producer-Consumer solution using Semaphores in Java | Set 2
Prerequisites - Semaphore in Java, Inter Process Communication, Producer Consumer Problem using Semaphores | Set 1 In computing, the producer–consumer problem (also known as the bounded-buffer problem) is a classic example of a multi-process synchronization problem. The problem describes two processes, the producer and the consumer, which share a c
5 min read
Classical Problems of Synchronization with Semaphore Solution
With the evolution of multi-processors, tasks suffer due to overheads and traffic. To manage the resources efficiently, synchronization is needed. Synchronization ensures perfect execution of processes and controlled access to shared resources. Synchronization in operating systems is often explained with the help of real-life examples. In this arti
4 min read
Communication between two process using signals in C
Prerequisite : C signal handling In this post, the communication between child and parent processes is done using kill() and signal(), fork() system call. fork() creates the child process from the parent. The pid can be checked to decide whether it is the child (if pid == 0) or the parent (pid = child process id).The parent can then send messages t
3 min read
Print numbers in sequence using thread synchronization
The problem is to synchronize n number of threads using pthread library. The idea is take thread count and print 1 in first thread, print 2 in second thread, print 3 in third thread, ..... print n in nth thread and again repeat from thread 1 infinitely. Prerequisite : Multithreading Examples : Input : Thread count Output : 1 2 3 ... thread count 1
2 min read
Implementing Directory Management using Shell Script
Directory management constitutes the functions dealing with organization and maintenance of various directories. Directories usually contain files of any type, but this may vary between file systems. The content of a directory does not affect the directory object itself. Some of the directory functions are: Navigation Absolute/ Relative Pathnames L
3 min read
Finding Network ID of a Subnet (using Subnet Mask)
In order to find network id (NID) of a Subnet, one must be fully acquainted with the Subnet mask. Subnet Mask: It is used to find which IP address belongs to which Subnet. It is a 32 bit number, containing 0's and 1's. Here network id part and Subnet ID part is represented by all 1's and host ID part is represented by all 0's. Example: If Network i
2 min read
Comparison on using Java for an Operating System instead of C
Java is a managed language which offers memory safety. In Java, pointers do not exist, so we cannot do pointer arithmetic on a function pointer. An application can invoke a method defined in a class through the class object. In Java, we cannot do unsafe typecast of an object to overwrite the method pointer with something else. An out of bound array
2 min read
Implementation of Non-Preemptive Shortest Job First using Priority Queue
Read here for Shortest Job First Scheduling algorithm for same arrival times.Shortest job first (SJF) or shortest job next, is a scheduling policy that selects the waiting process with the smallest execution time to execute next.In this article, we will implement the Shortest Job First Scheduling algorithm (SJF) using a priority queue, so that we c
12 min read
Parsing ambiguous grammars using LR parser
LR parser can be used to parse ambiguous grammars. LR parser resolves the conflicts (shift/reduce or reduce/reduce) in parsing table of ambiguous grammars based on certain rules (precedence and/or associativity of operators) of the grammar. Example: Lets take the following ambiguous grammar: E -> E+E E -> E*E E -> id Lets assume, the prece
3 min read
Apply changes to all the images in given folder - Using Python PIL
Given a dataset of raw images, which usually need some pre-processing, which one person has to do physically. It is generally a task that requires some repetitive operation to perform for each image. Well, we can easily automate this process using some simple Python code and some libraries with it. So without further adieu, let's see how to apply c
2 min read
Implementation of Least Recently Used (LRU) page replacement algorithm using Counters
Prerequisite - Least Recently Used (LRU) Page Replacement algorithm Least Recently Used page replacement algorithm replaces the page which is not used recently. Implementation: In this article, LRU is implemented using counters, a ctime (i.e., counter) variable is used to represent the current time, it is incremented for every page of the reference
8 min read
Implementation of SOP function using multiplexer
Given a SOP function and a multiplexer is also given. We will need to implement the given SOP function using the given MUX. There are certain steps involved in it: Step 1: Draw the truth table for the given number of variable function. Step 2: Consider one variable as input and remaining variables as select lines. Step 3: Form a matrix where input
1 min read
First Fit algorithm in Memory Management using Linked List
First Fit Algorithm for Memory Management: The first memory partition which is sufficient to accommodate the process is allocated.We have already discussed first fit algorithm using arrays in this article. However, here we are going to look into another approach using a linked list where the deletion of allocated nodes is also possible.Examples: In
15+ min read
Program for Best Fit algorithm in Memory Management using Linked List
Best fit algorithm for memory management: The memory partition in which there is a minimum loss on the allocation of the process is the best-fit memory partition that is allocated to the process.We have already discussed one best-fit algorithm using arrays in this article. However, here we are going to look into another approach using a linked list
15+ min read
Calculate server loads using Round Robin Scheduling
Given M servers that handle multiple requests having infinite computational capability and arrays arrivalTime[] and processTime[] of size N denoting the arrival time and load time of N requests in the following manner: Each server is numbered from 0 to (M - 1) and the requests are given in strictly increasing order of time.Each request i is assigne
14 min read
Design of 512x8 RAM using 128x8 RAM
If we see RAM physically then we notice that RAM is made up of a few chips. We can design the required RAM size using basic RAM chips. We can observe a basic RAM chip as follows: CS1: For chip select 1, the value should be 1CS2: For chip select 2, the value should be 0. Read and Write: Used for upcoming signals. If we have n bit address and m bit w
3 min read
How Communication happens using OSI model
The Open System Interconnection (OSI) model is a standard “reference model” created by an International Organization for Standardization (ISO) to describe how software and hardware components involved in network communication divide efforts and interact with each other. The OSI model defines a seven-layer set of functional elements, from physical i
4 min read
Control Signals Generation using Counter
In various digital applications(For example : hardwired control unit) control signals are needed to start, execute and step various operations in a particular time sequence.For this control signals are required and for the generation of control signals, a counter circuit is designed whose outputs are connected to a decoder. The decoder provides the
2 min read
Minimization of DFA using Myhill-Nerode Theorem
Minimization of DFA using Myhill-Nerode Theorem :Minimization of DFA is Required to obtain the minimal and equivalent version of any DFA which consists of minimum number of states possible. Myhill-Nerode theorem can be used to convert a DFA to its equivalent DFA with minimum no of states. This method of minimization is also called Table filling met
5 min read
Full Adder Using Demultiplexer
Full Adder is a combinatorial circuit that computes the sum and carries out two input bits and an input carry. So it has three inputs - the two bits A and B, and the input carry Cin, and two outputs - sum S and output carry Cout. Demultiplexer is a combinational circuit which has 1 input, n selection lines and generates 2n outputs. It is the revers
2 min read
Implementing 32:1 Multiplexer using 8:1 Multiplexers
A multiplexer is a digital combinational circuit that selects one out of several input lines and directs it to a single output line, hence often alternatively called a data selector. The selection of a particular input line out of several choices takes place on the basis of the selector lines. A multiplexer, in general, has n input lines, log2n sel
3 min read
Implementing Monitor using Semaphore
When multiple processes run at the same time and share system resources, the results may be different. This is called a critical section problem. To overcome this problem we can implement many solutions. The monitor mechanism is the compiler-type solution to avoid critical section problems. In this section, we will see how to implement a monitor us
3 min read
Shortest Job First (or SJF) CPU Scheduling Non-preemptive algorithm using Segment Tree
Shortest job first (SJF) or shortest job next, is a scheduling policy that selects the waiting process with the smallest execution time to execute next. SJN is a non-preemptive algorithm.   Shortest Job first has the advantage of having a minimum average waiting time among all scheduling algorithms.It is a Greedy Algorithm.It may cause starvation i
15+ min read
Finding the candidate keys for Sub relations using Functional Dependencies
We know how to find candidate keys for a relation already, you can check here Finding Attribute Closure and Candidate Keys using Functional Dependencies. But here we will learn to find out the candidate keys for a sub relation which is a little bit different from that of finding out candidate keys for a relation. Let see how to find it. What is Fun
4 min read
Running User Interface Thread in Android using Kotlin
User Interface Thread or UI-Thread in Android is a Thread element responsible for updating the layout elements of the application implicitly or explicitly. This means, that to update an element or change its attributes in the application layout ie the front-end of the application, one can make use of the UI-Thread. Realizing UI Thread: For example,
4 min read
Article Tags :