Monday, April 14, 2014

Readers Writers

Here is an implementation of Readers Writers solution although it has a major bug . . . .Can you find it??? 

ReaderWriter.java

public class ReaderWriter
{
public static void main(String[] args)
{
DB database = new DB(1);
Mutex mut = new Mutex(1);
Reader reader[] = new Reader[5];
Writer writer[] = new Writer[5];
for(int i=0;i<5;i++)
{
writer[i] = new Writer(i,mut,database);
new Thread(writer[i]).start();
}
for(int i=0;i<5;i++)
{
reader[i] = new Reader(i,mut,database);
new Thread(reader[i]).start();
}
}
}
class Reader implements Runnable
{
int rno;
DB database;
Mutex mut;
Reader(int rno, Mutex mut, DB database)
{
this.rno = rno;
this.mut = mut;
this.database = database;
}
public void run()
{
try
{
mut.downMutex(); // Enter Critical Section
database.incRC();
if(database.rc == 1) // i.e if its the First Reader
{
database.downDB(); // Put a lock on DB
}
mut.upMutex();     // Leave Critical Section
//Thread.sleep(2000);
System.out.println("Value read by Reader "+this.rno+" is :"+database.db); // Access the DB value
mut.downMutex(); // Again Enter Critical Section
database.decRC();
if(database.rc == 0) //If the Reader is done 
{
database.upDB(); // release the Lock on DB
}
mut.upMutex(); // Leave Critical Section
}
catch(Exception e){e.printStackTrace();}
}
}
class Writer implements Runnable
{
int wno;
int value;
DB database;
Mutex mut;
Writer(int wno, Mutex mut, DB database)
{
this.wno = wno;
this.mut = mut;
this.database = database;
}
public void run()
{
try
{
this.value = this.wno + 10 ;  // Creating some data
database.downDB();    // Trying to put lock in Database
database.db = this.value;     // Writing to the Database
System.out.println("Writer "+this.wno+" is writing "+this.value+" to Database");
database.upDB();  // Releasing the lock
}
catch(Exception e){e.printStackTrace();}
}
}

class Mutex
{
int mutex;
Mutex(int mutex)
{
this.mutex = mutex;
}
void upMutex()
{
this.mutex = 1;
}
void downMutex()
{
while(this.mutex==0);
this.mutex = 0;
}
}
class DB
{
int dbLock;
int db;
int rc = 0; // Reader Count
DB(int dbLock)
{
this.dbLock = dbLock;
}
void upDB()
{
this.dbLock = 1;
}
void downDB()
{
while(this.dbLock == 0);
this.dbLock = 0;
}
void incRC()
{
this.rc = this.rc + 1;
}
void decRC()
{
this.rc = this.rc - 1;
}
}

No comments:

Post a Comment