Professional Documents
Culture Documents
018 OS Reader Writer
018 OS Reader Writer
//Roll No :- UCE2022018
//READER WRITER
import java.util.concurrent.Semaphore;
class RWA {
static Semaphore mutex = new Semaphore(1); //mutex = 1
static Semaphore wrt = new Semaphore(1); //wrt = 1
static int readCount = 0;
//static variables so that all objects of Reader and writer can access the
same variables
//passing 1 to semaphore implies that only one object can access the variable
at a time
static class Reader implements Runnable { //Reader Thread
//Implements runnable interface as runnable interface is used to
execute concurrent threads
public void run() {
//runnable interface has only one function run which is
implemented here
try {
//Acquire Section
mutex.acquire(); //we have to wait till the time mutex is
not 1
//after it is unlocked the thread enters and decrements it
to 0 to lock it for itself again
//now no other thread can enter
//mutex lock ensures no two thread change read count
variable concurrently
readCount++; //reader added
if(readCount==1) //if its the first reader we have to check
if writer is writing
{
wrt.acquire();//we wait till writer does'nt release
the resource once it does we lock it for reader
}
mutex.release(); //after we are done changing readcount we
release mutes to allow other readers to be added
//Reading section
System.out.println("Thread
"+Thread.currentThread().getName() + " is READING");
//current thread is static method which returns current
executing thread
//getname is a method which returns the name of the thread
it is called by
Thread.sleep(1500);
//sleep method is used to pause a thread for few
milliseconds
System.out.println("Thread
"+Thread.currentThread().getName() + " has FINISHED READING");
//Releasing section
mutex.acquire(); //we again put lock to ensure no other
thread changes readcount variable
readCount--; //our reading is done so no. of readers are
decremented
if(readCount == 0) //if not readers are left
{
wrt.release(); //we also release the resource if any
writer want to access it
}
mutex.release(); //we release lock for changing readcount
variable
} catch (InterruptedException e) {
//this exception is thrown when a thread is waiting
sleeping or otherwise occupied
//and the thread is interrupted before or during the
activity
System.out.println(e.getMessage());
}
}
}
}
}
/*Output
*/